Click here to Skip to main content
Licence Ms-PL
First Posted 13 Oct 2001
Views 162,404
Downloads 814
Bookmarked 33 times

A C++ STL String Tokenizer

By | 13 Oct 2001 | Article
A C++ STL Tokenizer class capable to tokenize a string when the set of character separators is specified by another string

Introduction

The class CTokenizer I am presenting in this article is capable of tokenizing an STL string when the set of character separators is specified by a predicate class. This is a very generally designed as a class template:

template <class Pred>
void CTokenizer { /*...*/ };

The separating (tokenizing) criteria being implemented in the argument predicate class Pred. The predicate classes are usually derived from unary_function<char, bool> and implement the () operator. I am giving only three examples of predicate classes: CIsSpace where the set of separators contains the white spaces 0x09-0x0D and 0x20, CIsComma where the separator is the comma character ',' and CIsFromString where the set of separators is specified by the characters in a STL string. Other predicate classes can be easily added as needed.

Implementation

First I will present the implemented predicates.

For the case when the separators are white spaces 0x09-0x0D and 0x20;

class CIsSpace : public unary_function<char, bool>
{
public:
  bool operator()(char c) const;
};

inline bool CIsSpace::operator()(char c) const
{
  // isspace<char> returns true if c is a white-space character 
  // (0x09-0x0D or 0x20)
  return isspace<char>(c);
}

For the case where the separator is the comma character ',':

class CIsComma : public unary_function<char, bool>
{
public:
  bool operator()(char c) const;
};

inline bool CIsComma::operator()(char c) const
{
  return (',' == c);
}

For the case where the separator is a character from a set of characters given in a STL string:

class CIsFromString : public unary_function<char, bool>
{
public:
  //Constructor specifying the separators
  CIsFromString::CIsFromString(string const& rostr) : m_ostr(rostr) {}
  bool operator()(char c) const;

private:
  string m_ostr;
};

inline bool CIsFromString::operator()(char c) const
{
  int iFind = m_ostr.find(c);
  if(iFind != string::npos)
    return true;
  else
    return false;
}

Finally the string tokenizer class implementing the Tokenize() function is a static member function. Notice that CIsSpace is the default predicate for the Tokenize() function.

template <class Pred=CIsSpace>
class CTokenizer
{
public:
  //The predicate should evaluate to true when applied to a separator.
  static void Tokenize(vector<string>& roResult, string const& rostr, 
                       Pred const& roPred=Pred());
};

//The predicate should evaluate to true when applied to a separator.
template <class Pred>
inline void CTokenizer<Pred>::Tokenize(vector<string>& roResult, 
                                            string const& rostr, Pred const& roPred)
{
  //First clear the results vector
  roResult.clear();
  string::const_iterator it = rostr.begin();
  string::const_iterator itTokenEnd = rostr.begin();
  while(it != rostr.end())
  {
    //Eat seperators
    while(roPred(*it))
      it++;
    //Find next token
    itTokenEnd = find_if(it, rostr.end(), roPred);
    //Append token to result
    if(it < itTokenEnd)
      roResult.push_back(string(it, itTokenEnd));
    it = itTokenEnd;
  }
}

How to use

The following code snippet is showing some simple usage examples, one for each one of the implemented predicates:

//Test CIsSpace() predicate
cout << "Test CIsSpace() predicate:" << endl;
//The Results Vector
vector<string> oResult;
//Call Tokeniker
CTokenizer<>::Tokenize(oResult, " wqd \t hgwh \t sdhw \r\n kwqo \r\n  dk ");
//Display Results
for(int i=0; i<oResult.size(); i++)
  cout << oResult[i] << endl;
//Test CIsComma() predicate
cout << "Test CIsComma() predicate:" << endl;
//The Results Vector
vector<string> oResult;
//Call Tokeniker
CTokenizer<CIsComma>::Tokenize(oResult, "wqd,hgwh,sdhw,kwqo,dk", CIsComma());
//Display Results
for(int i=0; i<oResult.size(); i++)
  cout << oResult[i] << endl;
//Test CIsFromString predicate
cout << "Test CIsFromString() predicate:" << endl;
//The Results Vector
vector<string> oResult;
//Call Tokeniker
CTokenizer<CIsFromString>::Tokenize(oResult, ":wqd,;hgwh,:,sdhw,:;kwqo;dk,", 
                                          CIsFromString(",;:"));
//Display Results
cout << "Display strings:" << endl;
for(int i=0; i<oResult.size(); i++)
  cout << oResult[i] << endl;

Conclusion

The project StringTok.zip attached to this article includes the source code of the presented CTokenizer class and some test code. I am interested in any opinions and new ideas about this implementation.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

George Anescu

Web Developer

Romania Romania

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralStatic function tokenizer() PinmemberMember #277113815:15 9 Jan '07  
AnswerRe: Static function tokenizer() Pinmember69614:47 9 Apr '07  
GeneralVS 2005 Changes & bug fix PinmemberTerry.Kelly7:06 12 Oct '06  
GeneralVS 2005: bug solution Pinmembersirnowy2:15 11 Aug '06  
QuestionAny ideas on 'escaping' a character ? PinmemberGarth J Lancaster16:22 5 Sep '05  
AnswerRe: Any ideas on 'escaping' a character ? Pinmemberhaightasbury19:56 7 Feb '06  
GeneralRe: Any ideas on 'escaping' a character ? PinmemberGarth J Lancaster22:31 7 Feb '06  
GeneralSeparate the file attributes PinmemberIAMR20:32 16 Jul '04  
GeneralString Tokenizer PinmemberTheSolver5:09 22 Jul '03  
GeneralRe: String Tokenizer PinmemberHatemMostafa19:31 18 Dec '04  
GeneralUnicode PinmemberAdam Pond0:56 5 Apr '02  
GeneralTry boost tokenizer PinmemberRobin22:43 14 Oct '01  
GeneralRe: Try boost tokenizer PinmemberAnonymous22:25 18 Oct '01  
GeneralRe: Try boost tokenizer PinmemberAnonymous5:41 19 Apr '02  
It's there today.WTF | :WTF:
 
www.boost.org
GeneralLooks quite complicated... PinmemberPetr Prikryl22:29 14 Oct '01  
GeneralRe: Looks quite complicated... PinmemberMr.Prakash5:26 30 Nov '05  
Questionstrtok ? PinmemberAnonymous22:25 14 Oct '01  
AnswerRe: strtok ? PinmemberAnonymous22:57 14 Oct '01  
GeneralRe: strtok ? PinmemberHatemMostafa19:34 18 Dec '04  
AnswerRe: strtok ? PinmemberWilliam E. Kempf4:24 15 Oct '01  
GeneralRe: strtok ? PinmemberAnonymous4:48 15 Oct '01  
GeneralRe: strtok ? PinmemberAliff3:41 2 Sep '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120529.1 | Last Updated 14 Oct 2001
Article Copyright 2001 by George Anescu
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid