2

I have seen some very popular questions here, on StackOverflow about splitting a string in C++, but every time, they needed to split that string by the SPACE delimiter. Instead, I want to split an std::string by the ; delimiter.

This code is taken from a n answer on StackOverflow, but I don't know how to update it for ;, instead of SPACE.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "And I feel fine...";
    istringstream iss(sentence);
    copy(istream_iterator<string>(iss),
             istream_iterator<string>(),
             ostream_iterator<string>(cout, "\n"));
}

Can you help me?

Victor
  • 13,914
  • 19
  • 78
  • 147
  • There are answers in http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c?rq=1 – chris Jan 18 '14 at 18:19
  • 1
    Read about [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline). – Some programmer dude Jan 18 '14 at 18:19
  • 1
    You can create your own iterator which wraps around `std::getline(in >> std::ws, part, ';')`. – David G Jan 18 '14 at 18:20
  • 1
    Actually, the answer you took your code from is right above (when ordered by votes) an answer that splits it with any delimiter. – chris Jan 18 '14 at 18:45
  • 1
    You can find different solutions and explanations here: http://www.cplusplus.com/faq/sequences/strings/split/ – Tob Jan 18 '14 at 20:12

1 Answers1

2

Here is one of the answers from Split a string in C++? that uses any delimiter.

I use this to split string by a delim. The first puts the results in a pre-constructed vector, the second returns a new vector.

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;
    split(s, delim, elems);
    return elems;
}

Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:

std::vector<std::string> x = split("one:two::three", ':');
Community
  • 1
  • 1
NirMH
  • 4,769
  • 3
  • 44
  • 69