C++ Snippet

Split a String by Delimiter

Difficulty: Medium

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.

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

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.