Posted by: Cirilo Meggiolaro | 03/16/2009

Tip of the day #153 – TextElementEnumerator class

The TextElementEnumerator class available under the System.Globalization namespace provides functionality to enumerate elements of a string. The class does not have any constructor available so to create a new instance we need to use the static GetTextElementEnumerator method available under the StringInfo class.

Properties available

  • object Current: Read-only property that retrieves the current text element in the string;
  • int ElementIndex: Read-only property that retrieves the index of the text element that the enumerator is currently positioned over.

Methods available

  • string GetTextElement(): Gets the current text element in the string. The difference between the return value of this method and the Current property is that the method is going to retrieve a new string with the current text element while the Current property will retrieve an object that you will have to cast when necessary.
  • bool MoveNext(): Advances the enumerator to the next text element of the string. If elements on the sequence are over it returns false. Otherwise, returns true. So, the easiest way to loop through all items is to code a while loop based on the return of the MoveNext method;
  • void Reset(): Sets the enumerator to its initial position.

How to…

The following example shows how get a TextElementEnumerator object and loop through all items in a string.

/// Defines a string.
string text = “Tip of the day #153 – TextElementEnumerator class”;

/// Gets a text enumerator using the static GetTextElementEnumerator method.
TextElementEnumerator txtEnum = StringInfo.GetTextElementEnumerator(text);

/// Sets the enumerator to its initial position.
txtEnum.Reset();

/// Loops through all characters
while (txtEnum.MoveNext())
{
    /// Displays each character.
    Console.WriteLine(“{0}:\t{1}”, txtEnum.ElementIndex, txtEnum.Current);
}


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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: