TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# String Char Tips

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

String chars. 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. 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.

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

C# program that gets individual chars

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. 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. 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.

C# program that gets chars from different strings

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.

IsNullOrEmptyStatic Method

Internals. 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. 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 Chars

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf