Splitting a string into smaller pieces is one of the most common tasks in C++ programming, yet the standard library has no built-in split() function. You can achieve the same result using std::string methods like find() and substr(), or with the more modern std::stringstream and std::getline(). This guide shows you several reliable ways to split a string by a delimiter, with clear code examples you can copy and adapt.
What You’ll Need
- A C++ compiler (GCC, Clang, or MSVC) with C++11 or later support.
- A text editor or IDE (Visual Studio, Code::Blocks, VS Code, etc.).
- Basic familiarity with
std::stringand loops.
Step-by-Step
Method 1: Using std::string::find() and substr() (Most Flexible)
- Include the necessary headers. You need
<iostream>,<string>, and<vector>. - Create a function that takes a string and a delimiter. For example:
std::vector<std::string> split(const std::string& s, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; }Note: This uses
std::getline, which is simpler. For a purefind/substrversion, see below. - If you prefer
find()andsubstr()(no stream overhead):std::vector<std::string> split(const std::string& s, char delimiter) { std::vector<std::string> tokens; size_t start = 0; size_t end = s.find(delimiter); while (end != std::string::npos) { tokens.push_back(s.substr(start, end - start)); start = end + 1; end = s.find(delimiter, start); } tokens.push_back(s.substr(start)); return tokens; }This manually finds each delimiter and extracts the substring between them.
- Call the function in your main code. Example:
int main() { std::string data = "apple,banana,cherry"; std::vector<std::string> parts = split(data, ','); for (const auto& part : parts) { std::cout << part << std::endl; } return 0; }Output:
apple,banana,cherryon separate lines.
Method 2: Using std::stringstream and std::getline (Whitespace or Any Char)
- Include
<sstream>. - Use
std::getlineon a stringstream. This works exactly like reading from a file, but from a string:std::stringstream ss("one two three"); std::string token; while (std::getline(ss, token, ' ')) { std::cout << token << std::endl; }This splits by a single character (space here). For multiple whitespace, you can use
>>operator, but it only splits on whitespace. - To split by any whitespace (spaces, tabs, newlines): Use
ss >> tokenin a loop. This automatically skips leading whitespace.
Method 3: Using C++17 std::string_view (Efficient, No Copies)
- Requires C++17 or later. Include
<string_view>. - Create a split function that returns
std::vector<std::string_view>. This avoids copying substrings, which is faster for large strings:std::vector<std::string_view> split(std::string_view s, char delimiter) { std::vector<std::string_view> tokens; size_t start = 0; size_t end = s.find(delimiter); while (end != std::string_view::npos) { tokens.push_back(s.substr(start, end - start)); start = end + 1; end = s.find(delimiter, start); } tokens.push_back(s.substr(start)); return tokens; }Note: The string_view points to the original string, so the original must outlive the tokens.
Method 4: Using std::ranges (C++20, Optional)
- If you use C++20, you can use
std::ranges::views::split. Example:#include <ranges> #include <string> #include <vector> int main() { std::string s = "a,b,c"; auto split_view = s | std::views::split(','); std::vector<std::string> parts; for (auto part : split_view) { parts.emplace_back(part.begin(), part.end()); } }This is concise but requires a recent compiler.
Common Mistakes
- Forgetting to handle the last token. In the
find()/substr()method, after the loop you must add the substring from the last delimiter to the end. Forgetting this drops the final piece. - Using
std::getlineon a stream that is already at EOF. Make sure the stream is fresh. - Assuming
std::string::findreturns the position of the delimiter correctly. It returnsstd::string::nposif not found; check for that. - Ignoring empty tokens. If your string has consecutive delimiters (e.g., “a,,b”), the methods above will produce an empty string token. Decide if you want to skip them or keep them.
- Using
char*and C functions likestrtokonstd::string.strtokmodifies the original string and is not thread-safe. Avoid it unless you really need C-style.
Tips
- Choose the right method: For simple splits with a single character,
find()/substr()is fast and clear. For splitting on whitespace,stringstreamis convenient. For performance, usestring_view. - Handle leading/trailing delimiters. If your string starts with a delimiter, the first token will be empty. You can skip empty tokens by checking
if (!token.empty())before pushing. - Consider using
std::istringstreamfor line-based splitting. It’s often easier to read. - For multiple delimiters (like comma and space), you can replace them with a single delimiter first, or use a regex. But regex is slower; only use it if necessary.
- Always test with edge cases: empty string, single character, no delimiter, consecutive delimiters.
Troubleshooting
- Compilation error: ‘getline’ is not a member of ‘std’. Make sure you included
<string>and<sstream>if using stringstream. - Wrong output: missing last element. Double-check that you push the final substring after the loop. In the
find()method, the lasts.substr(start)is crucial. - Infinite loop. If you forget to update
startorend, the loop never terminates. Ensurestartmoves past the delimiter. - Empty tokens appear. If your delimiter appears consecutively, you’ll get empty strings. If you don’t want them, add a condition to skip.
- Performance issues with large strings. Using
substr()creates copies. Switch tostring_viewto avoid copies.
Frequently Asked Questions
Can I split a string by a string delimiter (like “||”)?
Yes. Use std::string::find with a string argument instead of a char. For example, s.find("||") and then use substr with the length of the delimiter.
How do I split a string into individual characters?
You can iterate over the string with a range-based for loop: for (char c : s) { ... }. That gives you each character as a char, not a string. If you need a vector of single-character strings, use std::string(1, c).
Is there a built-in split function in C++?
No, the C++ standard library does not provide a generic split() function. You have to implement it or use third-party libraries like Boost’s boost::split.
How do I split a string by multiple delimiters (e.g., comma or semicolon)?
You can replace all delimiters with a single one first (e.g., replace ‘;’ with ‘,’), then split by that single delimiter. Alternatively, use std::regex to split on a pattern like [,;].
Does splitting work with Unicode strings?
Yes, but be careful. std::string handles bytes, not characters. For UTF-8, splitting by a delimiter that is a multi-byte character requires careful handling. Consider using std::wstring or a library like ICU for full Unicode support.
What is the fastest way to split a string?
Using std::string_view and find() is generally the fastest because it avoids allocating new strings. However, if you need to store the tokens as std::string, you’ll have to copy them eventually. For most cases, the difference is negligible.
Related
- Shortcut to Switch Tabs? The Complete Guide
- Butterfly Life Cycle Worksheet: Free Printables & How to Use Them
- By Means of an Update? Meaning & Real Usage
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Change Slide Size in PowerPoint to A4 PaperTo change a PowerPoint presentation to A4, open it in the desktop app, select Design > Slide Size…
- How to Rotate Text in Microsoft ExcelTo rotate text in Microsoft Excel, select the cell or cells, then choose Home > Orientation and pick…
- Excel Find and Replace Shortcut: Keys, Options, and TipsIn Excel for Microsoft 365 on Windows, press Ctrl+H to open Find and Replace, then enter the text…
- Basic Accounting Concepts for Reading a Balance SheetA balance sheet summarizes what a business owns, what it owes, and the owners’ residual interest at a…
- How to Group Rows in Excel Online: A Step-by-Step GuideTo group rows in Excel Online, select their row numbers, choose Data > Group, and then use the…
- How to Freeze Multiple Rows in Excel Without Losing HeadersTo keep several rows visible while you scroll in Excel for Microsoft 365 on Windows, click the cell…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.