C++ How To Split a String
Split a String
Use a stringstream to split a string into words, and store them in a vector:
Example
string text = "apple banana cherry";
stringstream ss(text);
string word;
vector<string> words;
while (ss >> word) {
words.push_back(word);
}
for (string w : words) {
cout << w << "\n";
}
To split at another character, like a comma, use getline() with the character as the third argument:
Example
string text = "red,green,blue";
stringstream ss(text);
string part;
while (getline(ss, part, ',')) {
cout << part << "\n";
}
Explanation:ss >> word reads one word at a time, and skips the spaces.getline(ss, part, ',') reads everything up to the next comma.