2

Possible Duplicate:
Split a string into words by multiple delimiters in C++

I'm currently trying to read a file where each line has a variation of tabs and spaces separating key attributes that need to be inserted into a binary tree.

My question is: How do I split a line up using multiple delimiters using only the STL? I've been trying to wrap my head around this for the good part of the day to no avail.

Any advice would be very much appreciated.

Community
  • 1
  • 1
whippets
  • 21
  • 1
  • 2
  • 1
    There are many existing questions on this, e.g. http://stackoverflow.com/questions/7621727/split-a-string-into-words-by-multiple-delimiters-in-c and http://stackoverflow.com/questions/5505965/fast-string-splitting-with-multiple-delimiters – jogojapan Oct 26 '12 at 01:56
  • Take a look here http://stackoverflow.com/questions/236129/splitting-a-string-in-c There are also pure STL solutions. – David J Oct 26 '12 at 01:57

2 Answers2

9

Use std::string::find_first_of

vector<string> bits;
size_t pos = 0;
size_t newpos;
while(pos != string::npos) {
    newpos = str.find_first_of(" \t", pos);
    bits.push_back(str.substr(pos, newpos-pos));
    if(pos != string::npos)
        pos++;
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • 1
    what if the first character is one of these? Maybe start `pos` at -1, or do an initial search outside of the loop? – Xymostech Oct 26 '12 at 02:00
3

Using string::find_first_of() [1]:

int main ()
{
  string str("Replace the vowels in this sentence by asterisks.");
  size_t found;

  found = str.find_first_of("aeiou");
  while (found != string::npos) {
    str[found]='*';
    found=str.find_first_of("aeiou", found + 1);
  }

  cout << str << endl;

  return 0;
}
Murilo Vasconcelos
  • 4,677
  • 24
  • 27