- Introduction
- Creating and Using String Objects
- Formatting Strings
- Accessing Individual String Characters
- Analyzing Character Attributes
- Case-Insensitive String Comparison
- Working with Substrings
- Using Verbatim String Syntax
- Choosing Between Constant and Mutable Strings
- Optimizing StringBuilder Performance
- Understanding Basic Regular Expression Syntax
- Validating User Input with Regular Expressions
- Replacing Substrings Using Regular Expressions
- Building a Regular Expression Library
3.3. Accessing Individual String Characters
You want to process individual characters within a string.
Technique
Use the index operator ([]) by specifying the zero-based index of the character within the string that you want to extract. Furthermore, you can also use the foreach enumerator on the string using a char structure as the enumeration data type.
Comments
The string class is really a collection of objects. These objects are individual characters. You can access each character using the same methods you would use to access an object in most other collections (which is covered in the next chapter).
You use an indexer to specify which object in a collection you want to retrieve. In C#, the first object begins at the 0 index of the string. The objects are individual characters whose data type is System.Char, which is aliased with the char keyword. The indexer for the string class, however, can only access a character and cannot set the value of a character at that position. Because a string is immutable, you cannot change the internal array of characters unless you create and return a new string. If you need the ability to index a string to set individual characters, use a StringBuilder object.
Listing 3.4 shows how to access the characters in a string. One thing to point out is that because the string also implements the IEnumerable interface, you can use the foreach control structure to enumerate through the string.
Listing 3.4 Accessing Characters Using Indexers and Enumeration
using System; using System.Text; namespace _3_Characters { class Class1 { [STAThread] static void Main(string[] args) { string str = "abcdefghijklmnopqrstuvwxyz"; str = ReverseString( str ); Console.WriteLine( str ); str = ReverseStringEnum( str ); Console.WriteLine( str ); } static string ReverseString( string strIn ) { StringBuilder sb = new StringBuilder(strIn.Length); for( int i = 0; i < strIn.Length; ++i ) { sb.Append( strIn[(strIn.Length-1)-i] ); } return sb.ToString(); } static string ReverseStringEnum( string strIn ) { StringBuilder sb = new StringBuilder( strIn.Length ); foreach( char ch in strIn ) { sb.Insert( 0, ch ); } return sb.ToString(); } } }