C# String Char Tips

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.

This C# article shows how to access characters in strings. It uses the indexer built into the string type.

Example 1

Note

First, the best way to access a specific character is by using the square brackets on the string instance identifier. To get the first character, you can specify variable[0] and to get the last character, you can subtract one from the length, such as with variable[variable.Length - 1]. This is because the final offset in a string is always one less than its length, when length is one or more.

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

Using square brackets. Unlike in some languages like JavaScript, you 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. Characters in C# are larger than in older languages such as C++.

String type

Getting last character. To get the final character in a string, you can access the string's length property, which returns the count of characters in a string. Because the string buffer is zero-based, and is considered a SZ array or vector, you must access it starting with 0 and ending with the index of Length minus one.

Writing results to screen. All the method invocations to Console.Write and Console.WriteLine do is 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.Write Console.WriteLine

Example 2

Here we look at some of the complications of testing the characters in a string. 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. Additionally, 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

Getting characters from empty strings. The preceding program simply loops over several strings in the foreach iterative statement. The excellent 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 in the string. Finally, the program outputs the first and last characters of each string.

string.IsNullOrEmpty Method

Implementation

.NET Framework information

In the base class library, 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]. 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)
}

Loop over chars

Foreach loop construct

Another very 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 shown in this article. This site has a more useful article on the topic.

Loop Over String Chars

One-character substrings

Programming tip

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. I changed an important algorithm to use the char indexer instead of 1-character substrings, and the program became 75% faster.

Levenshtein Distance

Summary

The C# programming language

We looked at how you can access the individual characters in strings using the C# language. Additionally, 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. Finally, we noted a common mistake when accessing characters in strings.

Char Type
.NET