3

I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace with istringtream and by single delimiter with getline. How can I connect them all.

For instance:

input: This -is-a!,string;
output:

This  
is  
a  
string
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
vladfau
  • 1,003
  • 11
  • 22

3 Answers3

2

Why not just #include <cstring> and use std::strtok() in your C++ program?

Naruil
  • 2,300
  • 11
  • 15
1
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void SplitToVector(vector<string> &v, string dlm, string src){
    string::size_type p, start=0, len=src.length(); 

    v.clear();
    start = src.find_first_not_of(dlm);
    p = src.find_first_of(dlm, start);
    while(p != string::npos){
        v.push_back(src.substr(start, p-start));
        start = src.find_first_not_of(dlm, p);
        p = src.find_first_of(dlm, start);
    }
    if(len>start)//rest
        v.push_back(src.substr(start, len - start));
}

int main(void){
    char input[256] = "This -is-a!,string;";
    vector<string> v;
    int i, size;

    SplitToVector(v, "-!,;", input);
    //cout << input << endl;
    size = v.size();
    for(i=0; i<size; i++)
        cout << v.at(i) << endl;
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

I would recommend split in boost (string algorithm), see http://www.boost.org/doc/libs/1_53_0/doc/html/string_algo/usage.html#idp163440592.

Fredrik Jansson
  • 3,764
  • 3
  • 30
  • 33