Split Function in C++: Options and Examples

Formulas & functions · Updated November 22, 2026

C++ does not have a general-purpose std::split function or a split() member on std::string. In C++20, you can split a range with std::views::split; in older C++ versions, use a small loop, a stream, or a library that provides the behavior you need.

Why C++ Has No String Split Function

Many languages provide a built-in string method that returns a list of pieces. The C++ standard library has historically offered lower-level tools instead: search with find, take substrings with substr, or process characters with iterators. This lets a program choose whether to copy text, keep a view into existing text, handle empty fields, and interpret delimiters as characters or patterns.

C++20 added the ranges library, including std::views::split. It provides a standard way to traverse pieces without immediately building a container of new strings. It is a range adaptor, not a std::string member function, and it does not return a std::vector<std::string> by itself. If you need that concrete result, you can copy each piece into a string or use a helper function.

Split a String with std::views::split in C++20

Include <ranges> and pipe a character range into std::views::split. This example splits a string at each comma and prints the pieces:

#include <iostream>
#include <ranges>
#include <string>

int main() {
    std::string text = "red,green,blue";

    for (const auto& part : text | std::views::split(',')) {
        std::string token(part.begin(), part.end());
        std::cout << token << '\n';
    }
}

Compile in C++20 mode or later. For example, with a compiler using GCC or Clang, the command-line option is commonly -std=c++20; the exact command depends on your compiler and build setup. Each part is a range of characters, so constructing a std::string copies those characters into an owning string. If you only need to inspect or print the pieces, you can iterate over the characters in each part without making that copy.

The view is useful when you want to process tokens as you encounter them. It does not automatically trim whitespace, convert numbers, or validate the input. Those are separate tasks that should be handled according to the format your program accepts.

Choosing a Character or a Multi-Character Delimiter

The delimiter can be a single character, as in the comma example, or a range of characters. A multi-character delimiter is useful when a token is separated by a marker such as two colons. For example, with std::string text = "key::value::next"; and std::string_view delimiter = "::";, the split pattern is the whole :: sequence, not either colon on its own.

For the multi-character form, include <string_view> and pass the delimiter range to std::views::split, as in text | std::views::split(delimiter). The input string and delimiter must remain valid while the view is being used. In ordinary code where both are local variables that outlive the loop, this is straightforward. Avoid retaining a view beyond the lifetime of the text it refers to.

Be precise about what counts as a delimiter. Splitting on a space character does not, by itself, treat tabs or line breaks as separators. Splitting on a comma does not understand quoted commas in CSV. For a set of delimiter characters, such as any space, tab, or comma, a character-by-character loop or a suitable parsing routine may be clearer than trying to express the rule as one fixed pattern.

Using find and substr in Older C++ Versions

If your project uses C++17 or earlier, a loop around find and substr is a direct and portable approach. This function returns a vector of strings and preserves empty fields, including a final empty field when the input ends with the delimiter:

#include <string>
#include <vector>

std::vector<std::string> split(const std::string& text, char delimiter) {
    std::vector<std::string> tokens;
    std::size_t start = 0;

    while (true) {
        const std::size_t position = text.find(delimiter, start);
        if (position == std::string::npos) {
            tokens.emplace_back(text.substr(start));
            break;
        }
        tokens.emplace_back(text.substr(start, position - start));
        start = position + 1;
    }

    return tokens;
}

For example, split("a,,b,", ',') returns four strings: "a", an empty string, "b", and an empty string. An empty input produces one empty token in this implementation. Those choices are intentional, but another program may want to ignore empty fields instead. The important point is to define the expected behavior and test it rather than assuming every split utility follows the same policy.

This implementation copies each token into the result vector. That is convenient when the tokens need to live independently of the original input, but it takes additional memory and performs allocations as strings are created. For small configuration lines or command input, that simplicity is often worth it. For large data or performance-sensitive parsing, consider views or a parser designed for the format.

Other Options: Streams, Libraries, and Regular Expressions

std::getline is a compact option for reading fields separated by one character. It reads from a stream into a string until it reaches a delimiter, which is useful when the data is already being read from a file or stream. However, its behavior around empty fields can differ from a custom loop. In particular, code that must preserve a trailing empty field should check that behavior explicitly or use a loop with defined semantics.

Third-party libraries can provide more specialized splitting tools. Boost is one established C++ library collection, and other libraries may offer tokenizers or string utilities. Check the library documentation for whether results own their text, whether empty fields are kept, and how multi-character delimiters work. Those details matter when replacing one implementation with another.

Regular expressions are appropriate when the separator is a pattern, such as one or more whitespace characters, rather than one fixed character sequence. They can express complex rules, but are typically more involved than a simple delimiter loop and may have more overhead. Use them when the pattern genuinely needs regular-expression matching, not merely because a language in another ecosystem uses a regex-based split by default.

Empty Fields, Whitespace, and Common Pitfalls

Repeated delimiters create empty fields between them unless the chosen method filters those fields. For example, a comma-separated line such as red,,blue may represent a missing value, or it may be malformed input. Dropping the empty token without deciding which interpretation is correct can shift later fields and corrupt the meaning of the record.

  • Leading delimiters: A string such as ,first has an empty field before first under a preserve-empty-fields policy.
  • Adjacent delimiters: In one,,three, the middle field is empty if empty tokens are retained.
  • Trailing delimiters: Decide whether one,two, means a final empty field or whether the delimiter is simply ignored at the end.
  • Whitespace: Splitting on a comma leaves spaces around values intact. For "red, green", the second piece begins with a space.

Trimming is a separate operation. You can remove leading and trailing whitespace from each token with a helper based on character classification, taking care to pass characters as unsigned char to functions such as std::isspace. Do not assume that every byte-oriented whitespace rule handles Unicode text correctly; Unicode whitespace needs a more deliberate approach.

Another common mistake is treating a simple split as a complete file-format parser. CSV, for example, can include quoted fields containing commas and escaped quote characters. Splitting every line at every comma breaks such records. Use a CSV parser or implement the actual quoting rules when the input follows CSV syntax. The same principle applies to nested expressions, escaped delimiters, and network protocols.

How to Choose the Right Approach

Choose based on the delimiter, lifetime, and required result rather than only on how short the code looks. A practical guide is:

  • Use std::views::split in C++20 or later when you want standard range-based iteration and can keep the source text alive.
  • Use find and substr when you need clear, explicit behavior or must support an older language standard.
  • Use std::getline when reading a stream and splitting on a single character is sufficient.
  • Use a dedicated parser for structured formats with quoting, escaping, nesting, or validation requirements.
  • Use regular expressions when the delimiter is genuinely a pattern, while weighing their complexity against a simple loop.

Also consider what the caller needs. If it needs a vector that can be stored and passed around, produce an owning result such as std::vector<std::string>. If it only needs to examine each token once, a view or callback-style loop can avoid storing every token. Make ownership and lifetime visible in the function interface so callers do not accidentally keep references to temporary or destroyed input.

Frequently Asked Questions

Does C++ have a built-in std::split?
No general-purpose std::split function or std::string::split member exists in the standard library. C++20 provides std::views::split for range-based splitting; earlier standards can use a manual loop or streams.

Which header provides std::views::split?
Include <ranges> and use the C++20 language standard or later. The feature is in the std::views namespace.

How do I split a string by multiple characters?
Pass a range containing the full delimiter pattern to std::views::split, such as a std::string_view holding "::". A character delimiter and a multi-character delimiter are different rules; choose the one your input format specifies.

How can I keep empty tokens?
Define the expected policy and use an implementation that preserves empty fields. A find/substr loop can explicitly retain fields between adjacent delimiters and after a trailing delimiter. Check a library or stream approach rather than assuming it behaves identically.

Does std::views::split return a vector of strings?
No. It provides a range of subranges over the input. Construct strings from those subranges if you need independent, owning tokens; otherwise, process the ranges while their source text remains alive.

Practical Takeaway

For modern C++, start with std::views::split when its range-based behavior fits your task. For older code, or when you need precise control over empty fields and returned ownership, a short find/substr loop is easy to audit. In either case, decide how to handle whitespace, empty values, and malformed input before relying on the split result—especially when parsing a defined format rather than a simple delimiter-separated string.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.