C# Variables - Strings

In C#, a string variable is a variable with a String data type that holds a text value. That text is made up of a collection of characters. Double quotes ""are used to encase the character collection, forming the string.


String variables can be declared without initialization.


 string userName;
 string emailAddress;
 string greetingMessage;

Null vs. Empty

Since a string is a reference type, it's default value is "null," meaning that the variable has no reference to an object. A variable with a null value is not pointing to any allocation of memory. If you try to use the variable before giving it a value, your application will crash with a "NullReferenceException."


An "empty" string is an initialized String object that is pointing to a specific location of memory but contains no characters. An empty string is initialized with a set of double quotes with no characters between them

 string userName = "";
 string emailAddress = null; 
 Console.WriteLine(userName.Length);
 Console.WriteLine(emailAddress.Length);

If you run this code sample, the first line WriteLine would display a zero. The second WriteLine will crash the application.


The String object has a method named IsNullOrEmpty that will allow you to check to see if a variable is null.

 if (string.IsNullOrEmpty(emailAddress) == true)
 {
 Console.WriteLine("emailAdress has a null value");
 }
 else
 {
 Console.WriteLine(emailAddress.Length);
 }

Initializing String Variables

There are several ways you can initialize a string variable with a value.


String Literals

The most common way for someone just learning to code is to use a string literal, which means providing a literal string of text.

 string greetingMessage = "Hello, how are you doing today?";
 string userName = "Scott";
 string address = "123 Main Street, Here, USA 78956413";

Variable Assignment

You can also assign the value of a variable to another.

 string address = "123 Main Street, Here, USA 78956413";
 string billingAddress = address;
 string shippingAddress = address;

New String Object

Using the “new” keyword when initializing a string allows you to create a single string value from a collection of characters. It is also a convenient way to create a string made up of a repeating character. The following code will create a string value equal to 50 asterisks characters.

 string border = new string('*',50);

Combining Literals and Variables

Another way to initiate a variable is to combine string literals and variable values to create a new text value.


There are many ways to combine these two entities


Concatenation

With concatenation, the plus operator + is used to join values.

 string greetingMessage = "Hello" + userName + "how are you doing today?";
 
 string orderInstructions = "Bill To:" + billingAddress + " Ship To:" + shippingAddress;

You see here that a plus operator has been inserted between the literals and variables, joining the values into a single string. One drawback to this method is that if you don’t remember to add the spaces to your literals, your result string will not properly separate words. The value of greetingMessage is “HelloScotthow are you today?”


String.Format

The String object has a method named Format that allows you to build a string from a literal string and adding variables using placeholders in that literal to mark where the variable values will be inserted. The placeholders are created with the curly braces and an integer value used to determine which variable value is inserted.

string greetingMessage = String.Format("Hello {0}, how are you doing today?", userName);
 
string orderInstruction = String.Format("Bill To:{0} Ship To:{1}", billingAddress, shippingAddress);

The first variable will be inserted in the placeholder with the index of 0. The next variable will be inserted in the placeholder with the index of 1.


String Interpolation

String interpolation allows you to concatenate the values of the variable as part of the literal string without using the plus operator and additional quotes. Similar to String.Format the curly braces are used to tell Visual Studio to insert a value into the string.


The difference is that this time you are placing the variable inside the braces instead of a placeholder. You must use the $ symbol at the beginning of the string to indicate that interpolation is being used.

string greetingMessage = $"Hello {userName}, how are you doing today?";
string orderInstruction = $"Bill To:{billingAddress} Ship To:{shippingAddress}";


String Methods

Length is technically a property of the String object, not a method. The length property provides you with the number of characters that make up that string.


Length

Length is technically a property of the String object, not a method. The length property provides you with the number of characters that make up that string.

 string userName = "Scott";
 userName.Length; // Will return the number 5
 string address = "123 Main Street";
 address.Length; // Will return the number 15

Replace

The Replace method allows you to create a new string value by replacing all characters of one value with a character you provide.

This code will replace i’s in Mississippi with a’s.

 string state = "Mississippi";
 string stateReplaceI = state.Replace('i', 'a');

The value of stateReplaceI is “Massassappa”


ToLower/ToUpper

The ToLower and ToUpper methods allow you to create a new string value by copying the characters of a different string but changing the case of those characters to match the method you are using.


ToLower creates a string with all lowercase characters. ToUpper creates on with uppercase values.

 string userName = "Scott";
 string allUpper = userName.ToUpper();
 string allLower = userName.ToLower();

The value of allUpper is “SCOTT”. The value of allLower is “scott”.

Trim

The Trim method will remove all the spaces at the beginning and end of a string and create a new string without those spaces.

 string address = " 123 Main Street ";
 string trimmedAddress = address.Trim();

The value of trimmedAddress is “123 Main Street”


Zero-based Positioning

Before reading about the next few methods, you need to understand how C# reads a string. It was mentioned earlier in this post that a string is a collection of characters. When C# reads those characters, it starts from the beginning and traverses through the collection until it reaches the end.


The tricky part is that C# doesn’t see the first position of a string as 1. C# uses zero-based positioning, meaning that the first character of the string in the 0 position of the string. The second character has a position value of 1, and so on. Consider this variable declaration and initialization.

 string userName = "Scott";

For the string “Scott” the position values are:

0 – S

1 – c

2 – o

3 – t

4 – t

So even though userName.Length would return a 5 (the number of characters in the string); the last position in the string has a value of 4.

IndexOf/LastIndexOf

The IndexOf and LastIndexOf methods will search a string for a character you provide and provide the position of that character in the string.


IndexOf will start at the beginning of the string and stop when it finds the character. LastIndexOf will start at the end of the string and search backward, stopping when it finds the character.


Both methods return the position number of the character found.

 string state = "Mississippi";
 Console.WriteLine( state.IndexOf('i'));
 Console.WriteLine( state.LastIndexOf('i'));

It is essential to remember zero-based positioning when working with these methods. When you execute this code the console will display 1 for the IndexOf since the first “i” is the second letter of the string. 10 will be displayed for the LastIndexOf value.


Substring

Substring will allow you to create a new string from a segment of an existing string. When using Substring, you tell Visual Studio what position you want to start within the existing string (remember zero-based positioning). You then state how many characters you would like to copy from that string into your new one.

 string userName = "Silent John Smith";
 string middleName = userName.Substring(7, 4);

The value of middleName will be “John”.


Remove

The Remove method is the opposite of Substring. This method allows you to create a new string by cutting out the section of the text that you call out.

 string userName = "Silent John Smith";
 string realName = userName.Remove(7, 4);

The value of realName is “Silent Smith”. Notice that there are two spaces between “Silent” and “Smith”. If you wanted to get rid of those, you need to tell the Remove method to remove five characters, not four.



StartsWith

StartsWith lets you check to see if a string starts with a provide text value. This method returns a true or false value.


You will find more information about the method in the blog explaining “if statements.”


EndsWith

EndWith lets you check to see if a string ends with a provide text value. This method returns a true or false value.


You will find more information about the method in the blog explaining “if statements.”


Equals

The Equals method allows you to compare two strings to check for equality.


You will find more information about the method in the blog explaining “if statements.”


IsNullOrEmpty

IsNullOrEmpty will check if the provided string variable is empty or has a value of null.

You will find more information about the method in the blog explaining “if statements.”


Split

The Split method will split a single text value into an array of string, by splitting the text on the character you provide.


You will find more information about the method in the blog explaining “variable arrays.”


ToCharArray

ToCharArray splits the text value of the string into an array of characters. Every character in the string will be a separate element of the array.


You will find more information about the method in the blog explaining “variable arrays.”

65 views0 comments

Recent Posts

See All