How to Split a String in C++ (with Code Examples)

How-to basics · Updated November 23, 2026

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::string and loops.

Step-by-Step

Method 1: Using std::string::find() and substr() (Most Flexible)

  1. Include the necessary headers. You need <iostream>, <string>, and <vector>.
  2. 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 pure find/substr version, see below.

  3. If you prefer find() and substr() (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.

  4. 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, cherry on separate lines.

Method 2: Using std::stringstream and std::getline (Whitespace or Any Char)

  1. Include <sstream>.
  2. Use std::getline on 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.

  3. To split by any whitespace (spaces, tabs, newlines): Use ss >> token in a loop. This automatically skips leading whitespace.

Method 3: Using C++17 std::string_view (Efficient, No Copies)

  1. Requires C++17 or later. Include <string_view>.
  2. 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)

  1. 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::getline on a stream that is already at EOF. Make sure the stream is fresh.
  • Assuming std::string::find returns the position of the delimiter correctly. It returns std::string::npos if 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 like strtok on std::string. strtok modifies 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, stringstream is convenient. For performance, use string_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::istringstream for 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 last s.substr(start) is crucial.
  • Infinite loop. If you forget to update start or end, the loop never terminates. Ensure start moves 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 to string_view to 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

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

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

Spotted an error in this guide? Let us know.