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.
- pieces
- ["a"]
A comma in box 1. The piece is everything before it: "a". The next piece starts right after the comma.
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.
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 piecesHow many pieces does "a,,b," split into at the commas?
- A4
- B2
- C3
Show the answer
4. 3 commas give 4 pieces: "a", "", "b" and "".
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.
s = "a,b,,c", sep = "," → ["a", "b", "", "c"]
0 ≤ length ≤ 100,000 · sep is one character