To split a string in C++, use std::getline with a string stream for a single-character delimiter, or use std::string::find when you need more control over empty fields or a multi-character delimiter. The C++ standard library does not provide a general-purpose std::split function, so the best method depends on how your input should be divided.
What splitting means in C++
Splitting turns one string into a sequence of smaller strings, often called fields or tokens. For example, splitting "red,green,blue" at commas produces three parts: "red", "green", and "blue". The parts are commonly stored in a std::vector<std::string>, which grows as the program finds more of them.
Before choosing an implementation, decide what counts as a separator and what should happen when separators appear together or at the beginning or end. Splitting "a,,b," could produce four fields, including two empty ones, or only the nonempty values. Neither behavior is universally correct; it depends on what the input represents.
- Use
std::getlinefor a straightforward character delimiter. - Use
findfor a delimiter made of several characters or precise control of empty fields. - Use whitespace extraction when the goal is to read words separated by spaces, tabs, or newlines.
Split on one character with std::getline
A string stream lets std::getline read one field at a time. Its third argument is the delimiter character. This compact function splits a comma-separated string:
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& text, char delimiter) {
std::istringstream stream(text);
std::vector<std::string> fields;
std::string field;
while (std::getline(stream, field, delimiter)) {
fields.push_back(field);
}
return fields;
}
For example, calling split("oak,pine,birch", ',') returns a vector containing "oak", "pine", and "birch". The stream consumes each comma, so the comma is not included in the resulting fields. Include <sstream> for std::istringstream and <vector> for the result container.
This approach preserves empty fields between adjacent delimiters and before a leading delimiter. For example, "a,,b" yields "a", an empty string, and "b". However, a trailing empty field is not yielded: splitting "a,b," this way returns "a" and "b". An empty input also produces no fields. If those cases need different treatment, use a custom loop.
Use find for full control
std::string::find locates a separator, and substr extracts the characters before it. A loop can deliberately preserve leading, repeated, and trailing empty fields. This version also supports a delimiter that is more than one character:
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
std::vector<std::string> splitAll(std::string_view text,
std::string_view delimiter) {
if (delimiter.empty()) {
throw std::invalid_argument("delimiter must not be empty");
}
std::vector<std::string> fields;
std::size_t start = 0;
while (true) {
const std::size_t pos = text.find(delimiter, start);
if (pos == std::string_view::npos) {
fields.emplace_back(text.substr(start));
break;
}
fields.emplace_back(text.substr(start, pos - start));
start = pos + delimiter.size();
}
return fields;
}
With splitAll("a--b----", "--"), the result is "a", "b", an empty string, and an empty string. The final empty value is included because the loop performs one last extraction after the delimiter at the end. For empty input, this implementation returns one empty field. Those choices are consequences of the loop, not special rules imposed by C++.
The function accepts std::string_view, a non-owning view of characters available since C++17, but stores results as owning std::string objects. That means callers can safely keep the returned fields after the original input goes away. If instead the result stored views, those views would only remain valid while the original character storage remained alive and unchanged.
Split whitespace-separated words
If “split” means reading words separated by any whitespace, stream extraction is simpler than specifying a delimiter. With a string stream, repeated spaces, tabs, and line breaks act as separators, and empty tokens are not returned:
std::istringstream stream("one two\tthree");
std::vector<std::string> words;
std::string word;
while (stream >> word) {
words.push_back(word);
}
Here, words contains "one", "two", and "three". This is different from std::getline(stream, field, ' '), which uses a literal space as the separator. A tab is not a space character, and consecutive literal spaces can create empty fields with line-based extraction. Choose based on whether whitespace is a general separator or a meaningful character in the format.
Choose a method for the input
The right solution depends on the shape of the delimiter and the meaning of blank fields. Consider these questions before settling on an implementation:
- Is the delimiter one character? For commas, colons, or pipes,
std::getlineis often the clearest option. - Can it contain multiple characters? Use
findwith a string or string view, such as"::"or"<sep>". - Do empty fields matter? Test leading, adjacent, and trailing delimiters with your chosen method, then define the expected result explicitly.
- Do you want copies or views? Owning strings are convenient and independent of the input lifetime; views can avoid copying but require careful lifetime management.
- Is this a structured file format? A delimiter split may not correctly parse quoted values, escaped delimiters, or line breaks inside fields.
For small configuration values or simple input lines, a vector of strings is usually a practical result. For performance-sensitive code that processes a large string briefly, views may reduce allocations. Measure with representative data before adding that complexity: the simpler owning-string version is often easier to maintain.
C++20 ranges and other standard options
C++20 added ranges utilities, including std::views::split, which can represent split pieces as a lazy view rather than immediately building a vector of strings. It is useful when you want to process pieces in a range pipeline. The view does not own the source text, so the source must outlive its use. Converting pieces into stored strings still requires copying their characters.
There is no ordinary std::split(text, ',') function in the standard library. C++20’s ranges split view uses a range as its pattern, so a single-character separator is typically supplied as a one-character range, such as a std::string_view. Its iterator and conversion details can make it less direct for beginners than getline. If the project does not already use ranges, a small, clearly specified helper function may be easier to read. The standard library facilities available depend on the compiler’s C++ language mode and library implementation.
Common problems and misconceptions
A frequent surprise is assuming every splitting method treats empty fields identically. It does not. In particular, code that uses std::getline should not be assumed to preserve a final empty field. If a trailing separator represents a blank final column in your data, write a loop that includes it and add a test for that exact input.
Another mistake is trying to pass a string delimiter to the three-argument std::getline overload. That overload takes a single character, not a string such as "::". Use find for a multi-character delimiter. Also be careful not to use an empty delimiter in a search loop: it does not advance the starting position and can cause an infinite loop unless handled separately.
Finally, splitting is not the same as parsing. Splitting a line on commas cannot correctly interpret every CSV file, because CSV allows quoted fields that may contain commas, escaped quote characters, and other rules. Similarly, a colon split is not automatically a correct parser for every configuration syntax. When the input follows a formal format, use a parser designed for that format or implement its grammar rather than assuming separators are always literal.
Frequently Asked Questions
Does C++ have a built-in split function?
There is no general std::split function in the standard library. Common choices are std::getline with a string stream, a loop using find, or the C++20 ranges facility std::views::split.
How do I split a string by a comma?
Put the string in an std::istringstream and repeatedly call std::getline(stream, field, ','), appending each field to a vector. Use a custom loop if you must retain a trailing empty field.
How do I split by more than one character?
Search for the whole delimiter with find, extract the text before each match, then advance by the delimiter’s length. Check that the delimiter is not empty so the search loop always makes progress.
How can I split on spaces but ignore repeated spaces?
Use formatted stream extraction, such as stream >> word in a loop. It treats runs of whitespace as separators and does not produce empty words for repeated spaces or tabs.
Why does my split result omit the last empty value?
Some common loops, including the usual getline pattern, do not return a final empty field after a trailing delimiter. If that field matters, choose or write an implementation whose behavior explicitly preserves it, and test inputs such as "x,".
Related
- String Length in C++: size(), length(), and Examples
- Reverse a String in C++: std::reverse and Examples
- JavaScript split() Method: Syntax, Examples, and Tips
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Not Highlighting Selected Cell? Causes and FixesExcel normally marks the active cell with a colored border; when you select several cells, the rest of…
- Google Sheets Add Item to Dropdown: Steps and TipsTo add an item to a Google Sheets dropdown, select a cell that uses the dropdown, open Data…
- Embed Video in PowerPoint With HTML: Options That WorkPowerPoint does not turn pasted HTML into a video embedded on a slide. For a standard online video,…
- 5 Year Sales Forecast Excel Template: 5 Options to CompareFor a five-year plan, start with Smartsheet’s dedicated 5-Year Sales Forecast Template if you want a ready-made Excel…
- Excel Print Area Button Greyed Out? Causes and FixesIf Excel’s Print Area button is greyed out, first exit cell-editing mode and make sure only one worksheet…
- Make a Word Form Fillable but Not EditableTo make a Word form fillable but keep its layout and instructions from being edited, add form controls,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.