Code Snippets
/

Split a String by Delimiter

Split a String by Delimiter

C++ does not ship with a one-call `split` function, so this snippet shows three idiomatic alternatives: a `std::stringstream` plus `std::getline` walk for single-character delimiters, a `find`/`substr` loop for multi-character delimiters, and a regex-based split for full pattern flexibility. Pick stringstream for whitespace, find/substr for fixed strings, and regex only when the rules are genuinely complex.

C++
Medium
3 snippets
cpp-string-class
string-manipulation
strings

777 views

16

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

std::vector<std::string> splitChar(const std::string& s, char sep) {
    std::vector<std::string> out;
    std::stringstream ss(s);
    std::string token;
    while (std::getline(ss, token, sep)) {
        out.push_back(token);
    }
    return out;
}

int main() {
    auto parts = splitChar("alpha,beta,gamma,,delta", ',');
    std::cout << "parts size=" << parts.size() << "\n";
    for (const auto& p : parts) std::cout << "[" << p << "]\n";
    return 0;
}

std::getline(stream, out, delim) reads up to (and discards) the next occurrence of delim, leaving the rest of the stream for the next call. The pattern is identical to reading lines with std::getline(cin, line) (where the delimiter defaults to \n). It correctly preserves empty tokens between consecutive delimiters, which strtok does not. Use this for CSV without quoting, simple : PATH-style splits, or any single-character separator.