Learn / Strings

String parsing

Parsing means reading a string by its own rules: symbols with values, words split by spaces, runs of equal digits. Walk the string with an index, look ahead one character when the rule needs it, and build the answer as you go.

How to recognise it

  • The input follows a format (Roman numerals, words with extra spaces, a described sequence).
  • The meaning of a character depends on its neighbour (as in IV versus VI).
  • The output is produced by reading runs or tokens one at a time.

The idea in one picture

Read the string the way you would read it aloud: one token at a time, sometimes glancing at the next symbol before deciding what the current one means.

Three shapes

ShapeLoopProblem here
One symbol, peek at the nextfor i, compare value(s[i]) with value(s[i + 1])Roman to Integer
Tokens split by spacesskip spaces, then read a wordReverse Words in a String
Runs of equal charactersj walks to the end of a run starting at iCount and Say

Template: walking runs

i = 0
while i < n:
    j = i
    while j < n and s[j] == s[i]: j = j + 1
    the run is s[i .. j - 1], of length j - i
    i = j

The same "skip, then read" loop splits words: skip spaces, then read up to the next space.

Common mistakes

  • Looking ahead past the end of the string.
  • Splitting on a single space, which leaves empty words when spaces repeat.
  • Building the next term while still reading the current one, in the same variable.

Problems

0 of 3 solved

Check yourself

In a Roman numeral, when is a symbol subtracted?

What is the count-and-say term after 1211?

Reverse Words must handle " hello world ". What should come out?