Sign in

Split Keeping Empty Tokens

core

Implement vector<string> split_keep_empty(const string& s, char delim) that splits s on every occurrence of delim, keeping empty tokens.

One rule decides everything: the result has exactly one more token than there are delim occurrences in s. Every delimiter is a cut, every gap between cuts is a token, and an empty gap is an empty token:

  • a leading delim → leading empty token
  • a trailing delim → trailing empty token
  • k consecutive delim characters → k - 1 empty tokens between them
  • no delim at all → a single-element vector containing all of s

Example: split_keep_empty("a,,b,", ',') returns {"a", "", "b", ""}: four tokens for three commas, "a", the empty gap between the consecutive commas, "b", and the trailing empty. At the extreme, split_keep_empty(",,,", ',') returns {"", "", "", ""}, four empty tokens for three commas.

Input format: each test in tests/*.in is laid out as:

  • Line 1: the delimiter character delim.
  • Line 2: the string s to split, taken verbatim to the end of the line.

Test 02.in reads:

,
,x,

This is s = ",x," split on ,: a leading and a trailing comma, so the result is {"", "x", ""}.

Where you'll use it:

✦ Solution & editorial unlock with the pass.

Loading...