The CharEnumerator class has been designed to help iterating over characters in a string. Actually, the GetEnumerator method from the string object returns a CharEnumerator.
It’s important to say that the CharEnumerator is read-only and provides some methods to help the navigation.
Properties and methods
- char Current: Read-only property that retrieves the char existing in the current position within the string;
- object Clone(): Method that retrieves a copy of the full CharEnumerator object;
- bool MoveNext(): Moves the cursor to the next character within the CharEnumerator object;
- void Reset(): Moves the cursor to the position before the first character within the CharEnumerator object.
The following code snippet uses the MoveNext method and Current property to loop through all characters within a string and display it.
string s = “Tip of the day #120”;
CharEnumerator c = s.GetEnumerator();