To split a string based on a delimiter in C++, use std::getline with a std::stringstream when the delimiter is one character. When the text can be split by any one of several characters, such as a space, a comma or a semicolon, use find_first_of instead. Both give you a std::vector<std::string> of the pieces.
The short answer for one delimiter character
Load the text into a std::stringstream, then let getline stop at each delimiter. This example splits a colon-separated record:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string record = "Ada:36:London";
std::stringstream stream(record);
std::string piece;
while (std::getline(stream, piece, ':')) {
std::cout << piece << '\n';
}
}
The program prints Ada, 36 and London, one per line. The delimiter is never part of a piece. For more examples of reading with getline, see How to Use getline() and stringstream in C++.
Split on any of several characters
find_first_of returns the position of the first character in the text that matches any character in a set. Pass the set as a string, and the function splits on every character in it:
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> split_any(const std::string& text, const std::string& delimiters) {
std::vector<std::string> parts;
std::size_t start = 0;
std::size_t end = text.find_first_of(delimiters);
while (end != std::string::npos) {
if (end > start) {
parts.push_back(text.substr(start, end - start));
}
start = end + 1;
end = text.find_first_of(delimiters, start);
}
if (start < text.size()) {
parts.push_back(text.substr(start));
}
return parts;
}
int main() {
for (const std::string& word : split_any("red, green;blue gold", " ,;")) {
std::cout << word << '\n';
}
}
The program prints red, green, blue and gold. The two spaces before gold create no empty piece, because this version skips them. If you need find_first_of explained on its own, How to Find a Character in a String covers the basics of find.
Decide what empty pieces mean
The getline loop keeps empty pieces between two delimiters, and split_any drops them. Pick the behavior your data needs. A record such as name,,city may need the empty field kept, so each field stays in its place. A list of words usually reads better with the empty pieces dropped.
Test the edge cases
Try an empty string, a string with no delimiter, and a string that starts or ends with one. The getline version returns no pieces for an empty string. The find() approach returns one empty piece, because it always adds the text after the last delimiter.
Before you split user input, read the line first. How to Read String Input in C++ covers reading a full line with std::getline on std::cin, which is the usual first step.