CodeGym /Courses /Kotlin SELF /String normalization and parsing: trim*, lowercase/upperc...

String normalization and parsing: trim*, lowercase/uppercase, replace, split

Kotlin SELF
Level 9, Lesson 4
Available

1. Normalization before parsing

When we read a line via readln(), it feels like we got a “command” or “data”. In reality, we got raw text: with spaces, different letter case, random commas, extra separators, and sometimes input in the style of “I pressed space five times because I can”. Normalization is the step where we bring input to a clear standard so that parsing is predictable.

A good strategy here is like in the previous lecture, where we did “read → prepare → parse”. Now it is simply that “preparation” became more solid:

flowchart TD
    A["readln(): raw input"] --> B["trim(): clean up edges"]
    B --> C["normalize spaces/separators"]
    C --> D["normalize case (if needed)"]
    D --> E["split(): cut into parts"]
    E --> F["check size and part types"]

Note: we are not trying to make the string perfect; we do exactly enough so that the logic works reliably afterward. And yes, it is normal if normalization takes more lines of code than the actual useful work: a program is not only “do it”, but also “do it correctly”.

Normalize case: lowercase() and uppercase()

The next typical problem is letter case. One user will enter Add, another will enter ADD, a third will enter add, and a fourth will write aDd (and be proud of it). If you compare strings directly, all these variants are different. That is why, when we want to recognize a “command” or an “action type”, it is convenient to convert input to a single case.

It is important to distinguish: command and data are not the same thing. We typically normalize the command (for example, to lowercase), while the “product name” or a “comment” is sometimes better left as-is so you do not turn iPhone into iphone (though sometimes it is acceptable—it depends on the task).

Example: normalize the command, but keep the argument as-is:

fun main() {
    val rawLine = "  AdD   Milk  "
    val line = rawLine.trim()

    val parts = line.split(" ")
    val command = parts[0].lowercase()
    val item = if (parts.size >= 2) parts[1] else ""

    println("command='$command', item='$item'") // command='add', item='Milk'
}

Here we already used split(), but so far without normalizing spaces—and that will come back to bite us. For now, just lock in the idea: lowercase() and uppercase() are a way to make comparisons robust.

2. Remove spaces at the edges: trim*

Almost any user input starts and ends with spaces more often than we would like. It is not because people are bad—keyboards work that way, and everyone has different habits. So the first thing we usually do to a string before parsing is remove spaces at the edges. Kotlin has trim(), and if you need more control—trimStart() and trimEnd().

  • trim() — removes spaces from both ends of the string
  • trimStart() — removes spaces from the beginning of the string
  • trimEnd() — removes spaces from the end of the string

It is important to remember one thing: strings in Kotlin behave as “immutable” (meaning: methods return a new string). So raw.trim() does not change raw; it returns a new string. This is a common reason for code that “does not work”.

Example—let us look at the difference between the three methods:

fun main() {
    val raw = "   hello   "

    println(">" + raw.trim() + "<")       // >hello<
    println(">" + raw.trimStart() + "<")  // >hello   <
    println(">" + raw.trimEnd() + "<")    // >   hello<
}

Here you can notice a useful trick: I intentionally added > and < to visually see the spaces. It is a tiny “debug by eye” technique that saves a lot of time.

If you expect input like “command + arguments”, then trim() should almost always be the very first step. Otherwise, string comparisons suddenly stop matching: "add" and " add" are different strings.

3. Split the string into parts: split()

When the string becomes “clean” (at least more or less), we can cut it into parts. For that, there is split(...). In a basic scenario, you will very often see split(" ") — “split by spaces”.

The result of split() is a list of parts (with type List<String>). We are not going deep into collections yet (that will be much later), but we only need two facts: the result has size, and you can access elements by index parts[i]. Lists are zero-indexed: the first element is index 0, the last is size - 1.

Why you cannot immediately do parts[1]

It is very tempting to write:

val parts = line.split(" ")
val second = parts[1] // "it definitely exists!"

But users are unpredictable. They can enter just one word. Then parts[1] is out of bounds, and the program crashes.

The correct style at our current level is to check size before accessing:

fun main() {
    val line = "add"
    val parts = line.split(" ")

    val cmd = parts[0]
    val arg = if (parts.size >= 2) parts[1] else "(no argument)"

    println("cmd='$cmd', arg='$arg'") // cmd='add', arg='(no argument)'
}

It looks a bit longer, but it does not break for no reason. And “does not break for no reason” is one of the best compliments code can get.

4. Targeted replacements: replace() and replaceFirst()

When you have removed edge spaces and fixed the case, there is still lots of “small trash” left: extra commas, double spaces, random periods, or the user put a , instead of a space (because “that feels more familiar”). This is where replace(old, new) comes in.

replace(old, new) replaces all occurrences of old with new. And replaceFirst(old, new) replaces only the first occurrence. This matters because sometimes you want to “fix the format” once, and sometimes you really want to replace everything.

A mini-example to feel the difference:

fun main() {
    val s = "one-two-two"

    println(s.replace("two", "X"))      // one-X-X
    println(s.replaceFirst("two", "X")) // one-X-two
}

Normalizing multiple spaces without regex

A typical programmer pain point: a user enters multiple spaces in a row, and split(" ") starts behaving “not the way you expected”. The simplest strategy without regular expressions (we are not touching them today) is to “compress” repeated spaces in a loop:

fun normalizeSpaces(text: String): String {
    var s = text.trim()

    while (s.contains("  ")) {
        s = s.replace("  ", " ")
    }

    return s
}

fun main() {
    val raw = "   milk     2    30   "
    println(normalizeSpaces(raw)) // milk 2 30
}

Yes, it is not the fastest way on the planet. But for learning examples and for typical “single-line user input” it is more than enough. And most importantly: it is understandable. When code is understandable, it is easier to fix than “magic optimization”.

5. Parsing a purchase

Now let us tie everything into one small scenario and continue developing our learning console app. Let it (for now) parse one line, a “purchase record”, in the format:

<item> <qty> <price>

For example:

milk 2 30

We want the app to be patient and accept input like:

  Milk,   2   30

That is: extra spaces, a comma after the name, different letter case.

Step 1: normalization “as we agree”

Let us create a function that brings a string to a more stable form:

fun normalizePurchaseLine(raw: String): String {
    var s = raw.trim()

    // Allow the user to type commas: replace them with spaces
    s = s.replace(",", " ")

    // Compress multiple spaces down to one
    while (s.contains("  ")) {
        s = s.replace("  ", " ")
    }

    return s
}

fun main() {
    val raw = "  Milk,   2   30  "
    println(normalizePurchaseLine(raw)) // Milk 2 30
}

Note: we are not touching the case here on purpose. We keep the product name exactly as the user typed it. If later we need to compare names (for example, treat milk and Milk as the same), then we will separately decide what exactly (and where) to convert to lowercase().

Step 2: split into parts and validate the shape

Now let us write a function that takes a normalized string, splits it into parts, and checks that there are exactly three parts:

fun splitPurchase(line: String): List<String> {
    val normalized = normalizePurchaseLine(line)
    return normalized.split(" ")
}

fun main() {
    val parts = splitPurchase("  Milk,   2   30  ")

    println("parts.size=${parts.size}") // parts.size=3
    println("parts[0]='${parts[0]}'")   // parts[0]='Milk'
}

We use the fact that the result of split() is a list that has size and index access.

Step 3: convert parts to numbers and build the response

Quantity and price are numbers. We already have experience with toIntOrNull() and checking for null. Let us keep it simple: if a number does not parse, we honestly return an error message.

Let us make a function that returns a ready message (success or error). This is a convenient solution at the current level: one result string—and main just prints it.

fun parsePurchaseToMessage(line: String): String {
    val parts = splitPurchase(line)

    if (parts.size != 3) {
        return "Error: expected format '<item> <qty> <price>'"
    }

    val item = parts[0]
    val qty = parts[1].toIntOrNull()
    val price = parts[2].toIntOrNull()

    if (qty == null || price == null) {
        return "Error: qty and price must be integers"
    }

    val total = qty * price
    return "Purchase: $item, qty=$qty, price=$price, total=$total"
}

fun main() {
    println(parsePurchaseToMessage("  Milk,   2   30  "))
    // Purchase: Milk, qty=2, price=30, total=60
}

Notice how much calmer life became: main() no longer deals with trivia. It does not “chop up the string” and does not catch shape errors. It delegates that to a function and simply prints the result.

Step 4: normalize case where it is needed

A common question: “Can we make MILK, Milk, and milk count as the same?”. Yes. But it is better to do it consciously: we do not normalize “everything”, only what we plan to compare.

For example, let us create a “canonical item name” for internal calculations (for now, we will just show the idea in output):

fun main() {
    val item = "Milk"
    val canonical = item.lowercase()

    println("item='$item', canonical='$canonical'") // item='Milk', canonical='milk'
}

This idea will later be very useful for commands, categories, identifiers—anything that must match regardless of input. Just remember: you do not always need to convert user text to lowercase. Sometimes it ruins the “meaningful appearance” of the data.

6. Common mistakes

Error #1: call trim() and forget to store the result.
A very common scenario: you wrote line.trim() and then kept working with line. But trim() returns a new string, and the original stays the same. So either write val cleaned = line.trim(), or (if you need to update the variable) var line = line.trim().

Error #2: expect trim() to remove spaces inside the string.
trim() only works on the edges. If you have a string "milk 2 30", then after trim() the internal spaces will remain. For internal spaces you need separate logic (for example, the loop while (s.contains(" ")) s = s.replace(" ", " ")), as we did above.

Error #3: use split(" ") on a “dirty” string and be surprised by empty parts.
If there are many spaces in a row, splitting by a single space can produce unexpected results (up to “empty” elements), and your parser starts getting confused. The simplest fix at the current level is to normalize spaces first, and only then do split().

Error #4: take parts[1] and parts[2] without checking size.
Even if “by the assignment” the user must enter three parts, in real input they can enter one or two. Without checking size you get a crash due to out-of-bounds access. Lists are zero-indexed, and the last index is size - 1.

Error #5: compare commands without normalizing case.
If somewhere you check for "add", and the user enters "Add", the condition will not match. That is why commands should almost always be converted to lowercase() (or uppercase()) and then compared as normalized strings.

Error #6: mix up replace and replaceFirst.
Sometimes you need to replace only the first occurrence (for example, fix “one separator”), and sometimes you need to replace all occurrences. If you use replace() thinking it will replace just once, you can quietly corrupt data: the string changes “too much”, and the bug is not obvious.

Error #7: mix “normalization” and “parsing” into one unreadable blob.
Technically, you can write a monster like line.trim().lowercase().replace(...).split(...)..., but reading and debugging that is painful. Much calmer: a separate normalization function, then a separate split() step, then validation and parsing. Such code is easier to maintain and easier to extend.

1
Task
Kotlin SELF, level 9, lesson 4
Locked
Whitespace frames
Whitespace frames
1
Task
Kotlin SELF, level 9, lesson 4
Locked
Yes/No answer
Yes/No answer
1
Task
Kotlin SELF, level 9, lesson 4
Locked
Receipt from a String
Receipt from a String
1
Task
Kotlin SELF, level 9, lesson 4
Locked
One-line form
One-line form
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION