Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

String Tokenizer Class in C++

0.00/5 (No votes)
2 Nov 2001 1  
As C++ doesn't have Java Equivalent StringTokenizer class, I have implemented the class for my own and helps the beginners

Sample Image - String_Tokenizer_Class_in_C__.gif

Introduction

This class helps the user to tokenize the Long string by specifying delimiter. I thought this will be helpful to the programmers who are at beginning stage.

Code Listing

// Constructor that takes 2 arguments 

// first argument is of string type that to be tokenized. 

// second argument is of string type that is used as token separator 

// and default separator is space 

StringTokenizer::StringTokenizer(CString str,CString sep=" ") 
{ 
    index=0; 
    count=0; 
    CString str1=""; 
    for (int i=0;i<str.GetLength() && sep.GetLength()==1;i++) 
    { 
        if(str.GetAt(i)==sep.GetAt(0)) 
        { 
            elements.Add(str1); 
            str1=""; 
        } 
        else 
        { 
            str1+=str.GetAt(i); 
        } 
    } 
    elements.Add(str1); 
    count=elements.GetSize (); 
} 
// Method is used to fetch the tokens. 

CString StringTokenizer::getNextElement() 
{ 
    index++; 
    if(index==count) 
    { 
        throw CString("Index out of Bounds"); 
    } 
    return elements.GetAt(index-1); 
} 
//method used to fetch the count of tokens from the string 

int StringTokenizer::countElements() 
{ 
    return count; 
} 

//fetch the elements at given position 

CString StringTokenizer::elementAt(int index) 
{ 
    if(index>=count ||index<0) 
    { 
        throw CString("Index out of Bounds"); 
    } 
    else 
        return elements.GetAt(index); 
} 

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