-1

I want to separate string by character "," or ";".

std::string input = "abc,def;ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) { //how to add here ";"?
    std::cout << token << '\n';
}
karlosos
  • 1,034
  • 9
  • 25

3 Answers3

3

Use the Boost Tokenizer library:

boost::char_separator<char> sep(",;");
boost::tokenizer<boost::char_separator<char>> tokens(input, sep);
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • Including boost for this little peace of code? – Quest Aug 26 '14 at 11:21
  • @PaulR i don't think that he will use anything else from boost, so including boost just for tokenizer... – Quest Aug 26 '14 at 11:24
  • 3
    I still don't see what the objection is - if you're serious about writing C++ code then boost should be part of your weaponry. And of course you only need to include the parts of boost that you need, and these are mostly header-only, i.e. no libraries. – Paul R Aug 26 '14 at 11:26
  • 1
    There's also `boost::split` and `boost::is_any_of`. – Rapptz Aug 26 '14 at 11:28
  • 1
    @Rapptz: +1: yes, see [this answer](http://stackoverflow.com/a/236976/253056) – Paul R Aug 26 '14 at 11:29
1

what about old way style?

std::string string = "abc,def;ghi";
std::vector<std::string>strings;
std::string temp;
for(int i=0; i < string.length(); i++)
{
    if(string[i] == ',' || string[i] == ';')
    {
        strings.push_back(temp);
        temp.clear();
    }
    else
    {
        temp += string[i];
    }
}
strings.push_back(temp);

live demo

Quest
  • 2,764
  • 1
  • 22
  • 44
0

Using strsep in string.h from C library , you could do it like this:

std::string input = "abc,def;ghi";
const char* ss = intput.c_str();
const char token[] = ",;";

for (const char* part; (part = strsep(&ss, token)) != NULL;) {
    std::cout<< part << std::endl;
}
CollioTV
  • 684
  • 3
  • 13