Tokenize a string in c#

Do you need a way to tokenize a string and consume its contents by the way ?
Usage:

String source = "www.omarbettin.com/test/tokens";

while (source <> "")
    String token = GetNextToken(source, "/");

Results:
loop1: token = “www.omarbettin.com”; source = “test/tokens”;
loop2: token = “test”; source = “tokens”;
loop3: token = “tokens”; source = “”;

public class Utils
{
    public static String GetNextToken(ref String source, String token)
    {
        int p, l, s;
        String result;
        if (source == "")
            return "";

        p = source.IndexOf(token);
        if (p == -1)
        {
            result = source;
            source = "";
            return result;
        }
        l = source.Length;
        s = token.Length;

        result = source.Substring(0, p).Trim();

        source = source.Substring(p + s, l - p - s);

        return result;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *