C# String Chars

Char type

Strings contain characters. These char values can be accessed with an indexer expression in the C# language. We can store these chars in separate variables. We can also test against other string characters.

Indexer

Example

Length property

We access a specific character by using the square brackets on the string instance identifier. To get the first character, you can specify variable[0]. To get the last character, you can subtract one from the length.

Strings

Tip:This is because the final offset in a string is always one less than its length, when length is one or more.

String Length
Program that gets individual chars: C#

using System;

class Program
{
    static void Main()
    {
	// Get values from this string.
	string value = "Dot Net Perls";
	char first = value[0];
	char second = value[1];
	char last = value[value.Length - 1];

	// Write chars.
	Console.WriteLine("--- 'Dot Net Perls' ---");
	Console.Write("First char: ");
	Console.WriteLine(first);
	Console.Write("Second char: ");
	Console.WriteLine(second);
	Console.Write("Last char: ");
	Console.WriteLine(last);
    }
}

Output

--- 'Dot Net Perls' ---
First char: D
Second char: o
Last char: s
Squares

Using square brackets. We can access characters directly using the square brackets. You should assign the result from the square bracket expression to a char variable, which aliases a type from the System namespace, System.Char.

Tip:To get the final character in a string, you can access the string's length property.

And:Because the string buffer is zero-based, we access it starting with 0 and ending with the index of Length minus one.

With Console, we print some text and the character values to the terminal window. You can pass a character type directly to Console.WriteLine because WriteLine provides an overloaded method with an appropriate signature.

Console.WriteConsole.WriteLine

Example 2

Null keyword

Here we look at some complications. 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.

And:With empty strings, the Length is zero, so there are no available offsets for you to access in the string.

Program that gets chars from different strings: C#

using System;

class Program
{
    static void Main()
    {
	// 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);
	    }
	}
    }
}

Output

--- 'Dot Net Perls' ---
First char: D
Last char: s
--- 'D' ---
First char: D
Last char: D
--- '' ---
--- 'Sam' ---
First char: S
Last char: m

The program loops over several strings in foreach. The string.IsNullOrEmpty static method checks for strings that cannot have their characters accessed. It allows the enclosed block to execute only when there is one or more characters.

string.IsNullOrEmptyStatic Method

Internals

Framework: NET

In the BCL, the square brackets on the string type invokes the string's indexer property. An indexer is simply a property accessor that allows you to access the object's data using the square brackets, such as in variable[0].

And:In the .NET Framework, the chars are accessed in an internal method, not in managed code.

Char indexer

.property instance char Chars
{
    .get instance char System.String::get_Chars(int32)
}

Discussion

Foreach loop construct

Another common and important task in the C# programming language is 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.

Loop Over String CharsProgramming tip

Also, it is almost always a mistake to access a specific character in a string with the Substring method, but this problem is found in many programs. Instead, accessing the char directly is much faster and results in no allocations.

Info:I changed an important algorithm to use the char indexer instead of 1-character substrings. The program became 75% faster.

Levenshtein Distance

Summary

We accessed the individual characters in strings. We saw some issues relating to empty and null strings and trying to access their characters. We looked into the base class library to see how the char accessor is declared.


C#: String: Char