To split a C++ string into separate pieces, use std::getline with a string stream for a delimiter, then store the pieces in a std::vector<std::string>. C++ does not provide a built-in split() function for std::string; a vector is usually the right result because the number of pieces can vary.
#include <sstream>
#include <string>
#include <vector>
std::string text = "red,green,blue";
std::stringstream stream(text);
std::vector<std::string> parts;
std::string part;
while (std::getline(stream, part, ',')) {
parts.push_back(part);
}
After the loop, parts contains three strings: red, green, and blue. The best method depends on what counts as a separator, whether empty pieces matter, and whether the result must truly have a fixed size.
What “array” means in C++
People often use “array” to mean any collection of values, but C++ distinguishes fixed-size arrays from dynamically sized containers. A built-in array such as std::string items[3] has a size set when it is declared. std::array<std::string, 3> is the standard library’s fixed-size array type. Neither is a convenient default when a string can split into an unknown number of pieces.
std::vector<std::string> is a resizable sequence. It can hold zero, one, or many tokens and grows as pieces are appended. It also works naturally with standard algorithms and range-based loops. If you know the exact number of pieces in advance and need a fixed-size result, you can copy the values into a std::array after checking the count. Do not write past the array’s bounds when the input has more pieces than expected.
Split on whitespace
If the input is separated by spaces, tabs, or newlines, formatted extraction from std::istringstream is often simpler than specifying a delimiter. The stream reads one whitespace-separated token at a time:
#include <sstream>
#include <string>
#include <vector>
std::string text = " one two\tthree\n";
std::istringstream stream(text);
std::vector<std::string> words;
std::string word;
while (stream >> word) {
words.push_back(word);
}
This produces one, two, and three. Repeated whitespace does not create empty tokens, and leading or trailing whitespace is ignored. That is usually what you want for ordinary words or command-like input. It is not appropriate when spaces are meaningful data, such as in a quoted name like New York; that requires a parser with rules for quotes and escaping rather than simple whitespace splitting.
Split on a character delimiter
For a comma, pipe, colon, or other single-character separator, construct a std::stringstream and pass the delimiter as the third argument to std::getline. The loop reads up to one delimiter per iteration. It is useful for simple input such as a list of labels or a basic delimited record.
std::string text = "first|second|third";
std::stringstream stream(text);
std::vector<std::string> fields;
std::string field;
while (std::getline(stream, field, '|')) {
fields.push_back(field);
}
Here the separator is a single character, not a string of multiple characters. If the separator is :: or --, this overload does not treat the whole sequence as one delimiter. Use a search-based loop or a suitable parsing library for a multi-character separator. Also remember that splitting is only one step in parsing: a CSV file, for example, may allow quoted commas and escaped quotation marks, so splitting every line at every comma will not correctly parse every valid CSV record.
Decide how empty fields should behave
Empty fields are a frequent source of bugs. With a delimiter-based getline loop, consecutive delimiters can produce an empty field between them. For example, splitting "a,,b" on a comma gives a, an empty string, and b. However, a delimiter at the very end is not reliably represented as a final empty field by the usual loop: "a,b," commonly yields just a and b. If empty fields are significant, define and implement that behavior explicitly instead of assuming the stream loop preserves every one.
A simple find-based helper can preserve empty fields at the beginning, between separators, and at the end:
#include <string>
#include <vector>
std::vector<std::string> split_keep_empty(const std::string& text, char delimiter) {
std::vector<std::string> fields;
std::size_t start = 0;
while (true) {
const std::size_t position = text.find(delimiter, start);
if (position == std::string::npos) {
fields.push_back(text.substr(start));
break;
}
fields.push_back(text.substr(start, position - start));
start = position + 1;
}
return fields;
}
With this helper, "a,,b," produces four fields, with empty strings in the second and fourth positions. An empty input produces one empty field. That is a deliberate convention, not a universal rule; if an empty input should mean no fields in your program, add an early check and return an empty vector. Decide the behavior from the format you are processing and test it with representative inputs.
Choose a container that fits the result
For most splitting tasks, a vector is clearer and safer than trying to create a raw array whose length is determined at runtime. A standard vector owns its elements, records its size, and manages its storage. You can inspect the number of results with parts.size(), access an element with parts[index], or iterate without knowing the count first.
Use std::array only when the number of fields is fixed by the problem, such as exactly three coordinates. Validate that the split returned exactly three values before copying them. A C-style array with a size calculated from runtime input is not standard C++; some compilers accept variable-length arrays as an extension, but portable C++ code should use a vector for a runtime-sized collection.
If the input is large and you want to avoid copying each token, a different representation may help. C++17 provides std::string_view, a non-owning view of characters. Views can refer to sections of an existing string, but they do not own the characters. The original string must remain alive and unchanged for as long as the views are used. For small inputs or code where ownership should be straightforward, storing strings in a vector is often the better trade-off.
C++20 ranges as an alternative
C++20 adds std::views::split, which can split a range using a delimiter pattern without immediately building a vector of strings. This is useful when you want to process each piece as it is produced. The pieces are subranges into the original text, so they are not automatically independent std::string objects.
#include <ranges>
#include <string>
#include <vector>
std::string text = "red,green,blue";
std::vector<std::string> parts;
for (auto piece : text | std::views::split(',')) {
parts.emplace_back(piece.begin(), piece.end());
}
This example converts each subrange into an owned string and stores it in a vector, much like the stream solution. If you instead keep views or subranges, keep the original string alive for their entire use. C++20 ranges can be expressive, but they are not inherently more suitable for every task; the straightforward getline loop remains easy to read for a simple character delimiter.
Common problems and how to avoid them
- Using the wrong separator rule: Formatted stream extraction treats whitespace as separators;
getlinewith a character argument uses that character. Pick the behavior that matches the input rather than trimming or splitting indiscriminately. - Assuming split validates data: Splitting
"12,abc,30"only creates three strings. It does not confirm that each field is a number or that the number of fields is valid. Check field counts and convert values with appropriate error handling. - Forgetting empty tokens: Consecutive delimiters and trailing delimiters may matter in formats where field position is meaningful. Test inputs such as an empty string,
"a,,b", and"a,b,". - Expecting a multi-character delimiter: The
getlinedelimiter parameter is one character. Search for a full delimiter string if the separator has more than one character. - Using a view after its source is gone: A
std::string_viewdoes not own its data. Returning views into a local string leaves dangling references; return owned strings or ensure the source outlives every view.
For untrusted or structured input, splitting should not be mistaken for full validation. Define what malformed records mean, check limits if the input could be very large, and use a format-aware parser when the format has quoting, escaping, or nested structure. The split operation itself does not protect against those complications.
Frequently Asked Questions
Does C++ have a built-in string split function?
No. The standard std::string API does not have a general-purpose split() member. Common choices are a stream with std::getline, a custom loop using find, or C++20 ranges with std::views::split.
How do I split a string by a comma in C++?
Create a std::stringstream from the string, then repeatedly call std::getline(stream, field, ',') and append each field to a vector. Use a custom helper if a trailing comma must produce a final empty field.
How do I split a string by spaces?
Use std::istringstream and extract strings with stream >> word. This treats runs of whitespace as separators and skips leading and trailing whitespace. Use a different parser if spaces inside quoted fields must be preserved.
Can I split directly into a C++ array?
You can store the results in a fixed-size std::array when the expected number of pieces is known, but first verify that the result count matches. For an unknown number of pieces, use std::vector; it is the standard container designed to grow dynamically.
How do I split on more than one character?std::getline accepts a single character delimiter. For a delimiter such as ::, repeatedly locate the full substring with find, append the text before it, and advance past the entire delimiter. Specify separately whether empty fields should be retained.
Related
- Excell Battery Corporation: What It Sells and How It Works
- Balance GraphQL API: Availability and Alternatives
- Can You Play Split Fiction Solo? Co-op Options Explained
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Conditional Formatting With Dates: A Practical GuideTo conditionally format dates in Excel, select the cells, then choose Home > Conditional Formatting and either select…
- How to Create a Concentric Circle Diagram in Excel FastTo make a concentric circle diagram in Excel, insert several oval shapes, size each one smaller than the…
- Load Excel Power Query Into an Existing TableIn Excel for Microsoft 365 on Windows, a Power Query can load to an existing worksheet, but it…
- Google Sheets Apps Script Not Opening? Fixes to TryIf Apps Script is not opening from Google Sheets, open the spreadsheet in a desktop web browser and…
- Excel Power Query Not Responding? Fixes That WorkIf Excel Power Query is not responding, wait briefly to see whether a large refresh is still running,…
- Office Furniture Inventory Spreadsheet: Setup and TipsAn office furniture inventory spreadsheet is a structured list of the furniture your organization owns, where it is,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.