Divide string by delimiter and save each component to vector


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.