TheDeveloperBlog.com

Home | Contact Us

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

<< Back to C-SHARP

C# String Chars (Get Char at Index)

Access characters in strings with 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.IndexerStringsChar
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

Console: With Console, we print some text and the character values to the terminal window.

Console

Info: You can pass a char directly to Console.WriteLine because WriteLine provides an overloaded method with an appropriate signature.

Overload
C# program that gets individual chars using System; class Program { static void Main() { // Get values from this string. string value = "The Dev Codes"; char first = value[0]; char second = value[1]; char last = value[value.Length - 1]; // Write chars. Console.WriteLine("--- 'The Dev Codes' ---"); Console.Write("First char: "); Console.WriteLine(first); Console.Write("Second char: "); Console.WriteLine(second); Console.Write("Last char: "); Console.WriteLine(last); } } Output --- 'The Dev Codes' --- First char: D Second char: o Last char: s
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.

Here: The string.IsNullOrEmpty static method checks for strings that cannot have their characters accessed.

IsNullOrEmpty, IsNullOrWhiteSpaceStatic

Tip: IsNullOrEmpty allows the enclosed block to execute only when there is one or more characters.

C# program that gets chars from different strings using System; class Program { static void Main() { // Array of string values. string[] values = { "The Dev Codes", "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 --- 'The Dev Codes' --- First char: D Last char: s --- 'D' --- First char: D Last char: D --- '' --- --- 'Sam' --- First char: S Last char: m
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# 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
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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