3.3 Accessing Individual String Characters

 <  Day Day Up  >  

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();         }     } } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net