views:

94

answers:

5

I want to use string Tokenizer for CPP string but all I could find was for Char*. Is there anything similar for CPP string ?

Thanks in advance

A: 

Check out STL algos like *find_first_of*, *find_first_not_of* and so on to create a custom one.

Chubsdad
+3  A: 

You can do as said by chubsdad or use boost tokenizer : http://www.boost.org/doc/libs/1_44_0/libs/tokenizer/tokenizer.htm

Doing it by yourself is not so complicated if you're affraid by Boost.

Guillaume Lebourgeois
@Guillaume Lebourgeois: Here's +1 from chubsdad :)
Chubsdad
A: 

You should take a look at Boost Tokenizer

reko_t
+4  A: 

What do you mean by "token"? If it's something separated by any whitespace, the string streams is what you want:

std::istringstream iss("blah wrxgl bxrcy") 
for(;;) {
  std::string token;
  if(!(iss>>token)) break;
  process(token);
}
if(!iss.eof()) report_error();

Alternatively, if your looking for a a certain single separating character, you can replace iss>>token with std::getline(iss,token,sep_char).

If it's more than one character that can act as a separator (and if it's not whitespaces), a combinations of std::string::find_first() and std::string::substr() should do.

sbi
+1 for three alternatives
Chubsdad
@sbi: Is there any good reason for preferring `for(;;)` over `while(iss>>token)` (assuming `token` was declared before the loop)? In this example it would be one line shorter, and, in my opinion, at least not less readable.
Space_C0wb0y
@Space_C0wb0y: (I only now understood your comment. Well, at least I think I do...) I just happen to prefer a more local variable over the terseness of the `while` loop.
sbi
A: 

Try this snippet I found somewhere (maybe even around here?):

#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}
Gunnar