String
charsStrings contain characters. These char
values can be accessed with an indexer expression in the C# language. We can test and loop over chars.
Char
notesWe can store these chars in separate variables. We cannot mutate (assign) chars in a string
. But we can use them to build up new strings.
We access a character by using the square brackets. To get the first character, you can specify variable[0]. To get the last character, you can subtract one from the length.
string
is always one less than its length, when length is one or more.Console
, we print some text and the character values to the terminal window.using System; // Get values from this string. string value = "hat"; char first = value[0]; char second = value[1]; char last = value[value.Length - 1]; // Write chars. Console.WriteLine("FIRST: {0}", first); Console.WriteLine("SECOND: {0}", second); Console.WriteLine("LAST: {0}", last);FIRST: h SECOND: a LAST: t
When you have a string
that is null
, it does not point to any object data, and you cannot use the indexer on it. Therefore, the character accesses will not succeed.
Length
is zero, so there are no available offsets for you to access in the string.string.IsNullOrEmpty
static
method checks for strings that cannot have their characters accessed.IsNullOrEmpty
allows the enclosed block to execute only when there is one or more characters.using System; // Array of string values. string[] values = { "Dot Net Perls", "D", "", "Sam" }; // Loop over string values. foreach (string value in values) { // Display the string. Console.WriteLine("--- '{0}' ---", value); // We can't get chars from null or empty strings. if (!string.IsNullOrEmpty(value)) { char first = value[0]; char last = value[value.Length - 1]; Console.Write("First char: "); Console.WriteLine(first); Console.Write("Last char: "); Console.WriteLine(last); } }--- 'Dot Net Perls' --- First char: D Last char: s --- 'D' --- First char: D Last char: D --- '' --- --- 'Sam' --- First char: S Last char: m
An indexer is a property. It allows you to access the object's data using the square brackets, such as in variable[0].
.property instance char Chars { .get instance char System.String::get_Chars(int32) }
Often we need to loop over the individual characters in a string
. You can do this with the foreach
loop, or with the for iterative statement using the char
accessors.
string
with the Substring
method.char
directly is much faster and results in no allocations.char
indexer instead of 1-character substrings. The program became 75% faster.Characters in strings can be accessed, but not modified. We saw some issues relating to empty and null
strings and trying to access their characters.