DSA Factory
Free Strings lessonsStrings · Stage 4 · Parsing · Step 2

Cut at every separator

Split a line into pieces wherever a separator character appears. About 8 minutes.

A piece runs up to the next comma

A spreadsheet saved as text looks like "Asha,Mumbai,,28": fields separated by commas. Splitting it means cutting at every comma.

Remember where the current piece started. Walk the text; whenever you reach a comma, the piece is everything from the start up to, but not including, the comma. The next piece starts just after it.

At each comma: cut the piece, then start the next one after it.
s = "a,b,,c", sep = ","
a
0
,
1
b
2
,
3
,
4
c
5
starti
pieces
["a"]

A comma in box 1. The piece is everything before it: "a". The next piece starts right after the comma.

Move 1 of 4

Empty pieces are real

Two commas in a row mean an empty field, like a blank cell in a spreadsheet. Keep it: throwing it away would shift every later field into the wrong column.

And don't forget the last piece, after the final comma. Three commas always give four pieces, even when some of them are empty.

n separators: always give n + 1 pieces.
Keep empty pieces: or later fields slide into the wrong place.
In code
pieces = []
start = 0
for i, ch in enumerate(s):
    if ch == sep:
        pieces.append(s[start:i])
        start = i + 1
pieces.append(s[start:])
return pieces
Quick check

How many pieces does "a,,b," split into at the commas?

  1. A4
  2. B2
  3. C3
Show the answer

4. 3 commas give 4 pieces: "a", "", "b" and "".

Your problem

Split a line

You get a string and a one-character separator. Return the pieces between separators, in order, keeping empty pieces. A string with no separator is one piece; an empty string is one empty piece.

Example
s = "a,b,,c", sep = "," → ["a", "b", "", "c"]

0 ≤ length ≤ 100,000 · sep is one character

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve