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?

5
  • There are answers in stackoverflow.com/questions/236129/… Commented Jan 18, 2014 at 18:19
  • 1
    Read about std::getline. Commented Jan 18, 2014 at 18:19
  • 1
    You can create your own iterator which wraps around std::getline(in >> std::ws, part, ';'). Commented Jan 18, 2014 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. Commented Jan 18, 2014 at 18:45
  • 1
    You can find different solutions and explanations here: cplusplus.com/faq/sequences/strings/split Commented Jan 18, 2014 at 20:12

1 Answer 1

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", ':'); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.