Strings are collections of characters that are grouped together to form words or sentences. If it wasn’t for humans, computers would probably never have anything to do with strings. The fact is, however, that one of the primary jobs of a computer is to accept data from and present data to humans. For this reason, it is highly likely that any C# program is going to involve a considerable amount of code specifically designed to work with data in the form of strings.
Creating strings in C#
Strings consist of sequences of characters contained in a string object. A string object may be created using a number of different mechanisms.
A string may be declared but not initialized as follows:
string myString;
Alternatively, you can assign a literal value to a string in C# using the assignment operator:
string myString = "Hello World";
It is, of course, also possible to declare a string using implicit typing:
var myString = "Hello World";
Similarly, a new string may be created using the new
keyword and passing through the literal value to the constructor:
string myString = new String("Hello World");
String literals are placed within double quotes (as shown above). If the string itself contains double quotes, the escape character (\
) should precede the double-quote characters:
System.Console.WriteLine ("He shouted \"Can you hear me?\"");
Output:
He shouted "Can you hear me?"
Code language: JavaScript (javascript)
You can also instruct C# to treat all the characters in a string verbatim by prefixing the string with the @ character. When using @ notation, everything between the double quotes is treated as a raw string, regardless of whether new lines, carriage returns, backslashes, etc., are present in the text. For example:
System.Console.WriteLine (@"You can put a backslash \ here and a new line and tabs work too. You can also put in sequences that would normally be seen as escape sequences like \n and \t.");
Output:
You can put a backslash \ here
and a new line
and tabs work too.
You can also put in sequences that would normally be seen as escape sequences like \n and \t.
Code language: JavaScript (javascript)
If you are familiar with the heredoc
function of other programming languages, you will quickly notice that this is essentially the C# equivalent.
Obtaining the length of a C# string
If you need to identify the length of a C# string, you can do so by accessing the Length
property of the string object:
string myString = "Hello World"; System.Console.WriteLine ($"myString length = {myString.Length}");
Output:
myString length = 11
Treating strings as arrays
It is possible to access individual characters in a string by treating the string as an array (arrays were covered in the C# Arrays lesson).
By specifying the index value using subscripting syntax ([]
), you can access individual characters in a string (keeping in mind that the first character is at index position 0):
string myString = "Hello World"; System.Console.WriteLine(myString[0]); System.Console.WriteLine(myString[2]); System.Console.WriteLine(myString[4]);
Output:
H
l
o
It is important to note that strings are immutable (in other words, while an entirely new string literal may be assigned to the variable, you cannot change the individual characters in a string). To experience this limitation, try running the following code:
string myString = "Hello World"; myString[5] = '-';
When attempting to run the above code, you will have received an error from the compiler stating the following:
Property or indexer `string.this[int]' cannot be assigned to (it is read-only)
It is also possible to convert a string to an array of characters by making a call to the string object’s ToCharArray
method as follows:
string myString = "Hello World"; char[] charArray = myString.ToCharArray(); foreach (char c in charArray) { System.Console.WriteLine(c); }
Output:
H
e
l
l
o
W
o
r
l
d
String character iteration
Given that we can treat each character in an array as an array element, it should not surprise you to learn that we can iterate through the characters of a string using a foreach
loop as follows:
string myString = "Hello World"; foreach (char c in myString) { System.Console.WriteLine(c); }
Output:
G
o
o
d
b
y
e
W
o
r
l
d
Concatenating strings
Strings may be concatenated (i.e., joined together) simply by adding them together using the addition operator (+
).
We can, therefore, combine two strings as follows:
string myString = "Hello World."; System.Console.WriteLine (myString + " How are you?");
Output:
Hello World. How are you?
Alternatively, you can concatenate strings using the Concat()
instance method of the String
class. This method takes two strings to be joined as arguments and returns a new string containing the union of the two strings:
string myString1 = "If at first you don't succeed, "; string myString2 = "try, try again."; string myString3 = String.Concat(myString1, myString2); System.Console.WriteLine(myString3);
Output:
If at first you don't succeed, try, try again.
Comparing strings
C# provides several options if you need to compare one string with another. The most common option is to use the equality operator, as demonstrated in the example below:
string myString1 = "Hello World"; string myString2 = "Hello World"; if (myString1 == myString2) { System.Console.WriteLine("The strings match."); } else { System.Console.WriteLine("They strings not match."); }
Output:
The strings match
You can also compare strings in a similar way using the String.Equals()
instance method. This method takes as arguments to two strings to be compared and returns a Boolean result indicating whether or not the strings match:
string myString1 = "Hello world"; string myString2 = "Hello world"; if (String.Equals(myString1, myString2)) { System.Console.WriteLine("The strings match."); } else { System.Console.WriteLine("The strings do not match."); }
Output:
The strings match.
In the above example, we passed both strings through to the Equals()
method when performing the comparison. The Equals()
method can also be called on a string literal or string object to achieve the same result:
string myString1 = "Hello world"; string myString2 = "Hello world"; if (myString1.Equals(myString2, StringComparison.Ordinal)) { System.Console.WriteLine("The strings match."); } else { System.Console.WriteLine("The strings do not match."); }
Output:
The strings match.
So far, all of the comparisons we have explored have performed a case-sensitive comparison. When calling the Equals() method, you can also pass through a comparison type parameter. The type must be taken from the C# StringComparison
enumeration, which, among values for performing culture-sensitive comparison settings, includes the OrdinalIgnoreCase
value for case-insensitive comparisons:
string myString1 = "HELLO WORLD"; string myString2 = "Hello world"; if (String.Equals(myString1, myString2, StringComparison.OrdinalIgnoreCase)) { System.Console.WriteLine("The strings match."); } else { System.Console.WriteLine("The strings do not match."); }
Output:
The strings match.
The same approach also works when calling the Equals()
method directly on a string literal or object:
var result = "My String".Equals("my string", StringComparison.OrdinalIgnoreCase);
The String.Compare()
method provides yet another way to compare strings, though this method has some useful additional features. This method accepts as arguments the two strings to be compared and returns an integer value indicating how the strings relate to each other in relation to sort order. A result of 0 indicates that the strings match. A value of less than 0 indicates that the first string precedes the second string in the sort order. Finally, a result of greater than 0 indicates the second string precedes the first in the sort order:
string myString1 = "Bananas are yellow."; string myString2 = "Oranges are orange."; var result = String.Compare(myString1, myString2); if (result == 0) { System.Console.WriteLine("Strings match."); } else if (result < 0) { System.Console.WriteLine("myString1 precedes myString2 in sort order."); } else if (result > 0) { System.Console.WriteLine("myString2 precedes myString1 in sort order."); }
Output:
myString1 precedes myString2 in sort order.
Changing string case
The case of the characters in a string may be changed using the ToUpper()
and ToLower()
methods. Both of these methods return a modified string rather than changing the actual string. For example:
string myString = "Hello World"; string newString; newString = myString.ToUpper(); System.Console.WriteLine(newString); newString = myString.ToLower(); System.Console.WriteLine(newString);
Output:
HELLO WORLD hello world
Splitting a string into multiple parts
A string may be separated into multiple parts using the Split()
method. Split()
takes as an argument the character to use as the delimiter to identify the points at which the string is to be split. Returned from the method call is an array containing the individual parts of the string. For example, the following code splits a string up using the comma character as the delimiter. The results are placed in an array called myColors
and a foreach
loop then reads each item from the array and displays it:
string myString = "Red, Green, Blue, Yellow, Pink, Purple"; string[] myColors = myString.Split(','); foreach (string color in myColors) { System.Console.WriteLine(color); }
Output:
Red Green Blue Yellow Pink Purple
As we can see, the Split()
method broke the string up as requested, but we have a problem in that the spaces are still present. Fortunately, C# provides a method to handle this.
Trimming and padding strings
Unwanted leading and trailing spaces can be removed from a string using the Trim()
method. When called, this method returns a modified version of the string with both leading and trailing spaces removed:
string myString = " hello "; System.Console.WriteLine ("[" + myString + "]"); System.Console.WriteLine ("[" + myString.Trim() + "]");
Output:
[ hello ] [hello]
Code language: JSON / JSON with Comments (json)
If you only need to remove leading or trailing spaces, use either the TrimStart()
or TrimEnd()
method respectively.
The inverse of the trim methods are the PadLeft()
and PadRight()
methods. These methods allow leading or trailing characters to be added to a string. The methods take as arguments the total number of characters to which the string is to be padded and the padding character:
string myString = "hello"; string newString; newString = myString.PadLeft(10, ' '); newString = newString.PadRight(20, '*'); System.Console.WriteLine ("[" + newString + "]");
Output:
[ hello**********]
Code language: JSON / JSON with Comments (json)
String replacement
Parts of a string may be replaced using the Replace()
method. This method takes the part of the string to be replaced and the string with which it is to be replaced as arguments and returns a new string reflecting the change. The Replace()
method will replace all instances of the string:
string myString = "Hello World"; string newString; System.Console.WriteLine (myString); newString = myString.Replace("Hello", "Goodbye"); System.Console.WriteLine (newString);
Output:
Hello World Goodbye World