To parse tokens

The following code shows how to parse tokens and use an Enumerator to walk
through each token
.


public IEnumerator GetEnumerator() { return new TokenEnumerator(this); }

private class TokenEnumerator : IEnumerator {
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t) { this.t = t; }

public bool MoveNext() {
if (position < t.elements.Length - 1) {
position++;
return true;
} else {
return false;
}
}

public void Reset() { position = -1; }

public object Current {
get { return t.elements[position]; }
}
}

static void Main() {
Tokens f = new Tokens("This is a well-done program.", new char[] {' ','-'});
foreach (string item in f) {
Console.WriteLine(item);
}
}



Explanation

1. Inner class implements IEnumerator interface:
2. Declare the MoveNext method required by IEnumerator:
3. Declare the Reset method required by IEnumerator:
4. Declare the Current property required by IEnumerator:
5. Test Tokens, TokenEnumerator
6. Testing Tokens by breaking the string into tokens:



By
Nathan


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: