#98 – Using an Indexer to Get a Specific Character In a String
September 23, 2010 Leave a comment
In C#, you can use the indexer operator [ ], to get a specified character in a string.
The indexer takes a zero-based integer as an index into the string. 0 returns the first character and n-1 (where n is the length of the string) returns the last character.
string s = "ABCDE"; char c = s[0]; // A c = s[2]; // C (3rd char) c = s[4]; // E
Using a negative value for the index will result in an IndexOutOfRangeException being thrown.
Note that indexers work to extract Unicode characters only if they are 2-byte UTF16 characters. The indexer cannot retrieve a 4-byte surrogate pair.
string s = "A€C"; char c = s[1]; // Works: € s = "A𠈓C"; c = s[1]; // Doesn't work: unprintable character