#98 – Using an Indexer to Get a Specific Character In a String

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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: