Posted By

browny on 10/20/10


Tagged

String Vector token


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

drules


Divide string by delimiter and save each component to vector


 / Published in: C++
 

  1. void Tokenize(const string &str, vector<string> &tokens, const string &delimiters = " ")
  2. {
  3. // Skip delimiters at beginning.
  4. string::size_type lastPos = str.find_first_not_of(delimiters, 0);
  5. // Find first "non-delimiter".
  6. string::size_type pos = str.find_first_of(delimiters, lastPos);
  7.  
  8. while (string::npos != pos || string::npos != lastPos)
  9. {
  10. // Found a token, add it to the vector.
  11. tokens.push_back(str.substr(lastPos, pos - lastPos));
  12. // Skip delimiters. Note the "not_of"
  13. lastPos = str.find_first_not_of(delimiters, pos);
  14. // Find next "non-delimiter"
  15. pos = str.find_first_of(delimiters, lastPos);
  16. }
  17.  
  18. }

Report this snippet  

You need to login to post a comment.