StringTokenizer using C#


In this article explains about StringTokenizer using C# and StringTokenizer class implements the interfaces IEnumerable, IEnumerator.

This is a simple implementation of a String Tokenizer in C#. The target string to be tokenized and the tokens as char array can be used to create an instance of String Tokenizer. Once created it can be iterated over and over again using the foreach loop. It also demonstrates the usage of the IEnumerator interface to iterate through the internal array of strings, which is formed by spilting the target string only once using the string method spilt.

StringTokenizer class implements the interfaces IEnumerable, IEnumerator. An object of StringTokenizer can be created using the target string and tokens to used in the form a char array.


public class StringTokenizer : IEnumerable, IEnumerator
{
string[] tokensizedStrs;
int index = -1;
public StringTokenizer(string target, char[] tokens)
{
tokensizedStrs = target.Split(tokens);
}
public IEnumerator GetEnumerator()
{
return this;
}
object IEnumerator.Current
{
get
{
return tokensizedStrs[index];
}
}
bool IEnumerator.MoveNext()
{
if (++index >= tokensizedStrs.Length)
return false;
else
return true;
}
void IEnumerator.Reset()
{
index = -1;
}
}

Here is a test code snippet:

StringTokenizer strTokenizer = new StringTokenizer(".NET is less complex than J2EE", new char[] { ' ' });
foreach (string strTokenized in strTokenizer)
Console.WriteLine(strTokenized);


Comments

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