std::string has no split member. In C++20 use std::views::split: for (auto piece : std::views::split(text, ',')) visits each field, and std::string(piece.begin(), piece.end()) turns one into a string. For words separated by any whitespace, read them with std::istringstream and >>. Before C++20, loop on s.find(delim, start) and substr.
Splitting a string is the classic C++ gap: other languages have split(), C++ has half a dozen building blocks that each treat empty fields differently. std::views::split keeps every empty piece, >> and find_first_of drop them all, and std::getline keeps them except after a trailing delimiter. The sections below cover the C++20 view, splitting into words, a string delimiter with find, fields and lines with getline, and several delimiters at once, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1std::views::split (C++20)Recommended
std::views::split(text, delim) is a lazy range: it finds the pieces as you loop, and each piece is a small range of characters pointing into text. The delimiter can be one char or a whole string. Wrap it in a function that returns a std::vector<std::string> and you have the split other languages ship with. Taking both arguments as std::string_view accepts a std::string, a literal or another view without copying them, and it avoids the trap at the end of the example.
#include <iostream> #include <ranges> #include <string> #include <string_view> #include <vector> // Split on a delimiter string and copy each piece into a std::string std::vector<std::string> split(std::string_view text, std::string_view delim) { std::vector<std::string> parts; for (auto piece : std::views::split(text, delim)) { parts.emplace_back(piece.begin(), piece.end()); } return parts; } // Print the count, then each piece in brackets so empty pieces show up void print(const std::vector<std::string>& parts) { std::cout << parts.size() << ':'; for (const auto& p : parts) { std::cout << " [" << p << ']'; } std::cout << '\n'; } int main() { print(split("red,green,blue", ",")); // The delimiter can be more than one character print(split("a -> b -> c", " -> ")); // Empty pieces are kept: between two delimiters and after the last one print(split("a,,b,", ",")); // Delimiter not found: one piece, the whole input print(split("nope", ",")); // Empty input: no pieces at all print(split("", ",")); // No copies: each piece can be viewed as a std::string_view std::string line = "id=42;name=Ada"; for (auto piece : line | std::views::split(';')) { std::string_view field(piece.begin(), piece.end()); std::cout << field << " (" << field.size() << " chars)\n"; } // Trap: a string literal as the pattern includes its hidden '\0', // so ", " never matches and the whole input comes back as one piece std::string_view list = "x, y, z"; for (auto piece : std::views::split(list, ", ")) { std::string_view whole(piece.begin(), piece.end()); std::cout << "literal: [" << whole << "]\n"; } print(split(list, ", ")); // the helper takes a string_view, so no '\0' }
Output
The first two calls print 3: [red] [green] [blue] and 3: [a] [b] [c]. Empty pieces are kept, the one after a trailing delimiter included: "a,,b," gives 4: [a] [] [b] []. A missing delimiter gives 1: [nope], and empty input gives 0:, no pieces at all. The string_view loop prints id=42 (5 chars) and name=Ada (8 chars) without copying anything, but those views point into line, so they are valid only while line lives unchanged. The last two lines are the trap: passing the literal ", " straight to views::split makes the pattern the three characters ,, space and \0, which never occur, so it prints literal: [x, y, z], one piece. Through the string_view parameter the same call gives 3: [x] [y] [z]. In C++23, std::ranges::to<std::vector<std::string>>() collects the pieces in one line; this page compiles as C++20, hence the loop.
2Splitting into words: std::istringstream and >>
The most-asked version of the question is "how do I iterate over the words of a string?", and the answer is older than ranges. Put the string in a std::istringstream and read it with >>: each read skips any run of whitespace (spaces, tabs, newlines) and returns the next word, so there are no empty words and leading or trailing spaces don't matter. std::istream_iterator<std::string> does the same reads to fill a vector in one statement.
#include <iostream> #include <iterator> #include <ranges> #include <sstream> #include <string> #include <vector> int main() { std::string sentence = " ship it\tfast now "; // operator>> skips any run of whitespace: spaces, tabs, newlines std::istringstream in(sentence); std::string word; while (in >> word) { std::cout << '[' << word << ']'; } std::cout << '\n'; // The same words straight into a vector with istream_iterator std::istringstream in2(sentence); std::vector<std::string> words{std::istream_iterator<std::string>(in2), std::istream_iterator<std::string>()}; std::cout << words.size() << " words, last: " << words.back() << '\n'; // Splitting on ' ' instead: every extra space is an empty piece, // and the tab is not a delimiter at all int pieces = 0; for (auto piece : sentence | std::views::split(' ')) { std::cout << '[' << std::string(piece.begin(), piece.end()) << ']'; ++pieces; } std::cout << '\n' << pieces << " pieces\n"; }
Output
The loop prints [ship][it][fast][now] and the vector holds the same 4 words, last: now. Splitting the same text on ' ' gives 9 pieces, six of them empty, with the tab still inside "it\tfast" because only the space is a delimiter. Use >> for words and keep views::split for data with one exact delimiter. The same stream reads numbers too: int n; while (in >> n) splits "3 14 15" and converts each piece in one step.
3A string delimiter with find and substr
Before C++20, splitting on a delimiter of several characters means writing the loop yourself: find the delimiter from a start position, take the substr before it, and continue just past it. It works in every C++ standard and is easy to adapt. One popular answer instead erases each piece from the front of the string; that destroys the input and copies the rest of the string once per piece, so moving a start index is better.
#include <iostream> #include <string> #include <vector> // Works in every C++ standard: find the next delimiter, cut, move past it std::vector<std::string> split(const std::string& s, const std::string& delim) { std::vector<std::string> parts; if (delim.empty()) { // find("") matches at every position: without this guard // the loop below would never advance parts.push_back(s); return parts; } std::size_t start = 0; std::size_t end; while ((end = s.find(delim, start)) != std::string::npos) { parts.push_back(s.substr(start, end - start)); start = end + delim.size(); } parts.push_back(s.substr(start)); // the piece after the last delimiter return parts; } void print(const std::vector<std::string>& parts) { std::cout << parts.size() << ':'; for (const auto& p : parts) { std::cout << " [" << p << ']'; } std::cout << '\n'; } int main() { print(split("scott>=tiger>=mushroom", ">=")); print(split("a,,b,", ",")); // Unlike std::views::split, empty input gives one empty piece print(split("", ",")); // Split once, at the first delimiter only: keep the rest intact std::string setting = "url=https://x.dev/?a=1"; std::size_t eq = setting.find('='); if (eq != std::string::npos) { std::string key = setting.substr(0, eq); std::string value = setting.substr(eq + 1); std::cout << key << " -> " << value << '\n'; } }
Output
">=" splits into 3: [scott] [tiger] [mushroom], and empty pieces are kept as with the view: 4: [a] [] [b] []. The two disagree on empty input, though: this loop always pushes the piece after the last delimiter, so "" gives 1: [], one empty string, where views::split gave none. Decide which you want and test it. The empty-delimiter guard is not optional: find("", start) returns start, so the loop would never move. The last block splits only at the first =, which keeps a value that contains = whole: url -> https://x.dev/?a=1.
4Fields and lines with std::getline
std::getline(stream, field, ',') reads up to the next comma instead of the next newline, which makes a std::istringstream a short way to split on one character. It is also how you split text into lines: leave out the third argument and the delimiter is '\n'. Two behaviours catch people out: the trailing-delimiter case, and Windows line endings.
#include <iostream> #include <sstream> #include <string> #include <vector> int main() { // getline with a third argument reads up to that character std::istringstream csv("10,20,,40"); std::string field; std::vector<int> numbers; while (std::getline(csv, field, ',')) { std::cout << '[' << field << ']'; if (!field.empty()) { numbers.push_back(std::stoi(field)); } } std::cout << '\n' << numbers.size() << " numbers\n"; // Gotcha: a trailing delimiter does NOT give a last empty field std::istringstream trailing("a,b,"); int count = 0; while (std::getline(trailing, field, ',')) { ++count; } std::cout << "\"a,b,\" gives " << count << " fields\n"; // Lines: the default delimiter is '\n'. A Windows "\r\n" ending // leaves a '\r' at the end of the line, so strip it yourself std::istringstream text("alpha\r\nbeta\r\ngamma\n"); std::string line; while (std::getline(text, line)) { bool had_cr = !line.empty() && line.back() == '\r'; if (had_cr) { line.pop_back(); } std::cout << line << " (" << line.size() << " chars)"; std::cout << (had_cr ? " had \\r\n" : "\n"); } }
Output
The fields print as [10][20][][40]: an empty field between two commas is kept, and the loop skips it before std::stoi, which throws std::invalid_argument on an empty string (see converting a string to an int), leaving 3 numbers. But "a,b," gives 2 fields, not three: getline stops when the stream runs out, so nothing follows a trailing delimiter. For lines, each \r\n line keeps its \r until you remove it, which the output shows as alpha (5 chars) had \r, while gamma (5 chars) had a plain \n. The same loop over a std::ifstream reads a file; see reading a file line by line.
5Several delimiters: find_first_of and std::regex
To split on any of several characters, find_first_of(delims) finds the next delimiter and find_first_not_of(delims) skips a run of them. That is the behaviour people reach for strtok to get, without its problems: strtok writes \0 into your buffer, so it needs a writable char buffer, never a literal or c_str(), and it keeps hidden state between calls, so two loops cannot tokenize at once. When the delimiter is a pattern, use std::sregex_token_iterator with submatch -1, which yields the text between the matches.
#include <iostream> #include <regex> #include <string> #include <string_view> #include <vector> // Split on ANY of the characters in delims; runs of them count as one, // so there are never empty tokens (the way strtok behaves, minus its flaws) std::vector<std::string> tokenize(std::string_view s, std::string_view delims) { std::vector<std::string> tokens; std::size_t start = s.find_first_not_of(delims); while (start != std::string_view::npos) { std::size_t end = s.find_first_of(delims, start); tokens.emplace_back(s.substr(start, end - start)); start = s.find_first_not_of(delims, end); } return tokens; } void print(const std::vector<std::string>& parts) { std::cout << parts.size() << ':'; for (const auto& p : parts) { std::cout << " [" << p << ']'; } std::cout << '\n'; } int main() { std::string s = "go;rust, zig||c"; print(tokenize(s, ";,| ")); // A regex delimiter; submatch -1 means "the text between matches" std::regex delim("[;,|] ?"); std::vector<std::string> parts( std::sregex_token_iterator(s.begin(), s.end(), delim, -1), std::sregex_token_iterator()); print(parts); // the regex version keeps the empty piece in "||" }
Output
tokenize prints 4: [go] [rust] [zig] [c]: the ", " pair and the doubled || each count as one gap. The regex version prints 5: [go] [rust] [zig] [] [c], because a regex match is one delimiter and || holds two of them with nothing in between. Pick the one whose handling of empty pieces you want. std::regex is much slower than the find functions, so keep it for patterns that really need it. To strip spaces from pieces split on a plain comma, see trimming whitespace.
6Which should you use?
| Method | Empty pieces | Standard | Best for |
|---|---|---|---|
| std::views::split(s, delim) | Kept | C++20 | One char or string delimiter, no copies |
| istringstream >> word | Dropped | Any | Words separated by any whitespace |
| s.find + s.substr loop | Kept | Any | String delimiter before C++20, split once |
| std::getline(in, f, ',') | Kept, except a trailing one | Any | Simple fields, lines of text |
| find_first_of / find_first_not_of | Dropped | Any | Any of several delimiter characters |
| std::sregex_token_iterator | Kept | C++11 | Delimiters that are a pattern |
| strtok | Dropped | C | Avoid: writes into the input, hidden state |
Frequently asked questions
Does std::string have a split function?
No, not even in C++23. The standard tools are std::views::split (C++20), std::istringstream with >> or std::getline, and a find plus substr loop. Most code wraps one of them in a small split function that returns a std::vector<std::string>. C++23 adds std::ranges::to, so std::views::split(s, ',') | std::ranges::to<std::vector<std::string>>() collects the pieces in one expression, but that needs a C++23 compiler setting.
Why does std::views::split not split on my string literal?
A string literal such as ", " is an array that ends in a hidden \0, and views::split uses the whole array as the pattern, so it looks for comma, space and \0, which never occur, and you get the input back as one piece. Pass a std::string_view instead: std::views::split(text, std::string_view(", ")), or write ", "sv after using namespace std::literals;. A single char delimiter such as ',' has no such problem.
How do I split a string into a vector of ints in C++?
For numbers separated by whitespace, read them straight from a stream: std::istringstream in(s); int n; while (in >> n) v.push_back(n);. For another delimiter, split with std::getline(in, field, ',') and convert each field with std::stoi, skipping empty fields, because std::stoi("") throws std::invalid_argument. Use std::from_chars to reject input like 12abc: it reads the 12 too, but returns the position where it stopped, so you can check that the whole field was used.
Why does getline lose the last empty field after a trailing comma?
std::getline returns false once the stream has nothing left to read, so after the final comma there is no read that produces an empty field: "a,b," gives two fields, not three. If that empty field matters (CSV columns, for example), use std::views::split or a find loop, which keep it, or check whether the input ends with the delimiter and add an empty string yourself.
Should I use strtok to split a string in C++?
Avoid it. strtok overwrites each delimiter in your buffer with \0, so it needs a writable char buffer, never a string literal or c_str(), and it keeps the position in hidden static state, so nested or concurrent tokenizing breaks. A find_first_of / find_first_not_of loop gives the same result (runs of delimiters count as one, no empty tokens) on a std::string_view without touching the input.
How do I split a string into lines in C++?
Wrap it in a std::istringstream and loop on std::getline(in, line), which splits on \n and does not yield an empty line after a final newline. Text with Windows line endings keeps a \r at the end of each line, so check !line.empty() && line.back() == '\r' and pop_back() it before comparing lines.