Click here to Skip to main content
6,291,522 members and growing! (14,162 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Regular Expressions     Intermediate

StringTokenizer

By Werdna

StringTokenizer class that can be used for breaking up a string (or stream) into smaller strings.
C#, Windows, .NET 1.0, .NET 1.1, .NET 2.0VS.NET2003, Dev
Posted:7 Jul 2004
Views:90,374
Bookmarked:41 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
25 votes for this article.
Popularity: 5.79 Rating: 4.14 out of 5
4 votes, 16.0%
1

2
3 votes, 12.0%
3
4 votes, 16.0%
4
14 votes, 56.0%
5

Introduction

This is yet another implementation of string tokenizer. This tokenizer allows you to break strings to tokens. The following tokens are recognized:

  • WORD - series of alpha characters or _
  • NUMBER - decimal number
  • QUOTEDSTRING - string that starts with " and ends with " and uses "" as escape character
  • WHITESPACE - space or tab
  • EOL - end of line. Recognized Windows \r\n, Unix \n, or Mac \r
  • SYMBOL - any symbol character (customizable)

Each token contains line #, column #, kind, and string data.

Here is a small example of how it works:

string input = "hello \"cool programmer\", your number: 3.45!";

StringTokenizer tok = new StringTokenizer(input);
tok.IgnoreWhiteSpace = true;
tok.SymbolChars      = new char[]{',', ':'};

Token token;
do
{
    token = tok.Next();
    Console.WriteLine(token.Kind.ToString() + ": " + token.Value);
        
} while (token.Kind != TokenKind.EOF);

and the output will be:

Word: hello
QuotedString: "cool programmer"
Symbol: ,
Word: your
Word: number
Symbol: :
Number: 3.45
Unknown: !

Note that ! is returned as Unknown, because it wasn't defined as symbol. You can specify which characters are symbols by: tok.SymbolChars. You can also specify whether whitespace is ignored.

All the source code is included so you can customize and modify the tokenizer. This little section will explain on how to extend the tokenizer, so that you can parse your own custom tokens.

Suppose you want to read $string as special token called Variable, where Variable is $ followed by variable name: (ALPHANUMERIC | _)*. What you would do is add new value to TokenKind enum (in Token.cs):

enum TokenKind
{
...,
Variable
}

and in StringTokenizer inside of Next method, add new case right before default:

switch (ch)
{
    ...
    case '$':
    {
        return ReadVariable();
    }

    default:
    ...
}

then, you just need to write ReadVariable method.

protected Token ReadWord()
{
    StartRead();    // this marks the position of the beginning of the token


    Consume(); 
    // consume first character which is $. If you don't want $ to be returned

    // as part of Value of the token, just calls StartRead() after Consume


    while (true)
    {
        char ch = LA(0);    // look at next available character

        // if it's letter or underscore, we just

        // consume it and continue reading

        if (Char.IsLetter(ch) || ch == '_')
            Consume();
        else        // if not we break the loop

            break;
    }

    // CreateToken creates the token with line and

    // column positions and the value of the token

    // is going to be from the string that was started

    // when StartRead was called, until current position

    return CreateToken(TokenKind.Variable);
}

That's it!

Of course, this tokenizer is very simple right out of the box and easy to modify, but for more complicated parsing, it's much better to use lexer/parser generator tools like antlr (http://www.antlr.org/). This tokenizer is really easy to use and does not have big overhead.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Werdna


Member

Occupation: Web Developer
Location: United States United States

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 15 of 15 (Total in Forum: 15) (Refresh)FirstPrevNext
GeneralThat was useful Pinmember Muammar© 5:51 13 Apr '08  
GeneralThank you! Thank you! Thank you! Pinmember982731982739817239871928371298378:27 6 Dec '06  
GeneralDifferent quote character for strings... PinmemberNathan Baulch22:57 5 Jul '06  
Generalnice... Pinmemberfalfan13:37 26 Jun '06  
GeneralRe: nice... PinmemberWerdna14:00 26 Jun '06  
Generalcannot strip whitespaces PinmemberTim Julian6:41 15 Jun '06  
GeneralRe: cannot strip whitespaces PinmemberRavi Bhavnani7:50 15 Jun '06  
GeneralAlternative Pinmemberstefankruzel6:18 28 Sep '05  
GeneralRe: Alternative PinmemberWerdna7:49 28 Sep '05  
GeneralRe: Alternative Pinmemberdave.dolan17:34 1 Oct '06  
GeneralQuestion about string tokenizer PinmemberJames Brannan23:39 9 Aug '05  
GeneralRe: Question about string tokenizer PinmemberWerdna4:31 10 Aug '05  
GeneralRe: Question about string tokenizer PinmemberJames Brannan8:50 10 Aug '05  
GeneralGreat Pinmemberreinux17:11 16 Jul '04  
GeneralOoh! PinmemberdzCepheus17:57 14 Jul '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 Jul 2004
Editor: Sean Ewington
Copyright 2004 by Werdna
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project