1. Introduction
When you start parsing a string “in pieces,” you suddenly discover that a string is not a friendly little bag of cookies, but more like a cookie box that sometimes has no lid. The user can enter an empty string, forget the delimiter, type two spaces in a row, or write something “creative” altogether. In this lecture, we learn to write code so it doesn’t crash, but instead predictably chooses a behavior strategy.
Imagine your program is a cashier, and the user is a customer who sometimes speaks unclearly. The cashier shouldn’t faint at the phrase “uhh… well… bread… I guess.” They should ask again, or apply a default decision. String parsing is the same: we design ahead of time what to do if we “didn’t find it,” “went out of bounds,” or it’s “empty.”
2. Indexes and boundaries in a string
A string in Kotlin is a sequence of characters with indexes. Indexing starts at zero. That sounds familiar, but this is exactly where classic errors are born: “why can’t I get a character at index length?” and “why is lastIndex not length?”
It’s important to get used to the idea that length is the number of characters, and the last valid index is length - 1 (if the string isn’t empty).
So you don’t have to keep it in your head like a spell, it’s convenient to think like this: length is the “position after the last character.” It’s useful for operations like “cut to the end,” but it’s not suitable as a character index.
Here’s a small diagram worth picturing mentally when you slice a string:
String: "Kotlin"
Indexes: 012345
length = 6
lastIndex = 5
Mini-check in code (so your brain believes your eyes):
fun main() {
val s = "Kotlin"
println(s.length) // 6
println(s.lastIndex) // 5
println(s[0]) // K
println(s[s.lastIndex]) // n
}
If the string is empty (""), then length == 0, and lastIndex == -1. This is not a bug, but an honest warning: “there is no last element.”
3. indexOf(...): -1 means “not found”
When we look for a delimiter in a string (for example, '=', '@', ':'), we often start with indexOf. And here it’s important to accept the philosophy of Kotlin (and most languages in general): if an element isn’t found, you get -1. The program doesn’t crash. It’s simply a way to say: “I searched, but didn’t find it.”
That’s why a typical beginner mistake sounds like this: “I found the index, immediately did substring, and everything crashed.” It crashed because the index was -1, and substring(-1, …) is already an attempt to cut text starting from a position that doesn’t exist.
A simple email example:
fun main() {
val email = "alice@example.com"
val at = email.indexOf('@')
val domain = if (at >= 0) email.substring(at + 1) else "INVALID"
println(domain) // example.com
}
The point isn’t the email itself (email has its own rules), but the pattern: indexOf → check → only then slice.
4. substring(...): boundaries and “end is excluded”
substring is a powerful knife. And like any knife, it works great as long as you’re not waving it around blindly.
The most important rule:
- substring(start, end) takes characters from index start inclusive up to index end exclusive.
That is, end is the “stop position,” not the “last character.”
Let’s lock it in with a short example:
fun main() {
val s = "Kotlin"
println(s.substring(0, 1)) // K
println(s.substring(0, 2)) // Ko
println(s.substring(1, 4)) // otl
}
Why is this convenient? Because you can safely set end equal to length. That’s the “position after the last character,” and it’s a valid slicing boundary.
So this is fine:
fun main() {
val s = "Kotlin"
println(s.substring(0, s.length)) // Kotlin
}
But this is already a boundary error:
// s.substring(0, s.length + 1) // don't do this: you'll go out of bounds
substring(start) as a way to take the “tail”
Sometimes you don’t need to specify end, because “to the end of the string” is exactly what you want. There’s a form substring(start) for that.
It’s convenient when you’ve already found a delimiter and want everything after it:
fun main() {
val path = "/users/alice"
val slash = path.indexOf('/')
val tail = if (slash >= 0) path.substring(slash + 1) else path
println(tail) // users/alice
}
Yes, the example is intentionally “weird” (because '/' is at the beginning). But it shows the idea: substring(start) removes the need to think about length and “end is excluded.” You simply say: “give me everything from here to the end.”
5. Pattern: find the delimiter, check it, slice
Now we’ll assemble the main working pattern of this lecture. You need it everywhere: configs like key=value, commands like add:100:food, log lines, “name: value,” basically anything.
Algorithm in plain language:
- Find the delimiter (indexOf).
- If it’s not found, choose a behavior (return null, return a default, treat the whole string as the “key,” etc.).
- If it’s found, carefully slice the left and right parts.
Here’s a “key=value” example:
fun main() {
val line = "key=value"
val eq = line.indexOf('=')
val key = if (eq >= 0) line.substring(0, eq) else line
val value = if (eq >= 0) line.substring(eq + 1) else ""
println("key=$key, value=$value") // key=key, value=value
}
Notice: with one found index (eq) we extract both parts. This is not only shorter, but also safer: you won’t end up slicing the “key” by one rule and the “value” by another.
6. Input preparation: trim() and safe split
User input is almost always “dirty”: extra spaces, tabs, random line breaks, a trailing space, a leading space. And if you start parsing without preparation, you’ll get strange errors like “everything looks correct, but somehow the key is empty.”
That’s why the basic discipline looks like this: first trim(), then analyze.
fun main() {
val raw = " key=value "
val line = raw.trim()
val eq = line.indexOf('=')
val key = if (eq >= 0) line.substring(0, eq) else line
val value = if (eq >= 0) line.substring(eq + 1) else ""
println("key='$key', value='$value'") // key='key', value='value'
}
Here, the quotes in the output are purely a teaching trick: they help you visually spot spaces if any remain.
split(" ") and multiple spaces
When we want to split a string into “words,” we most often do split(" "). With clean input it works. But with input like "one two three" you suddenly get empty strings among the results. That’s because split(" ") literally splits on single spaces, and if there are several spaces in a row, there’s an “empty word” between them.
So in practice, when parsing commands and input, it’s almost always useful to do three steps: trim() → split(" ") → filter { it.isNotEmpty() }.
fun main() {
val raw = " one two three "
val parts = raw.trim()
.split(" ")
.filter { it.isNotEmpty() }
println(parts) // [one, two, three]
}
You’ll see this pattern constantly, because it turns “human input” into “computer tokens.” Functions for reading structured input are often written in a similar style.
7. Error strategies: marker vs null
Now an important design point: what do you do if the string “doesn’t match”?
There are two very common approaches.
- First approach — return a marker (for example, "INVALID" or an empty string) and continue. It can be handy if you’re generating a report and want to “show something.” But it’s dangerous because it’s easy to forget to handle the marker, and then "INVALID" unexpectedly flows through as if it were a normal value.
- Second approach — return null and force the caller to make a decision. This style is usually more reliable: you explicitly see that the result may be absent. We already know how to work with nullable types, so today this will be our main tool.
Let’s add a small parser function to our learning console app (a hypothetical expense tracker): “parse a key=value token.”
Function parseKeyValue(token: String): Pair<String, String>?
This function prints nothing and reads nothing; it just carefully parses a string and returns either a pair or null. This style is easy to test and reuse.
fun parseKeyValue(token: String): Pair<String, String>? {
val eq = token.indexOf('=')
if (eq < 0) return null
val key = token.substring(0, eq).trim()
val value = token.substring(eq + 1).trim()
if (key.isEmpty()) return null
return key to value
}
Notice the “safety points”:
- eq < 0 → immediately null; we don’t attempt to slice.
- substring(eq + 1) is safe only because eq >= 0. When eq == token.lastIndex, the value will be empty, but it won’t crash.
- key.isEmpty() — protection from cases like "=123".
Mini-check:
fun main() {
println(parseKeyValue("amount=120")) // (amount, 120)
println(parseKeyValue("=120")) // null
println(parseKeyValue("amount=")) // (amount, )
println(parseKeyValue("amount")) // null
}
Parsing a command: “read → prepare → parse”
Now let’s assemble a small (but realistic) piece of a console interface for our expense tracking app.
We want the user to enter commands in a style like:
- add amount=120 category=food note=coffee
- add amount=999 category=tech note=keyboard
We won’t complicate formatting, storage, reports, etc. today. Our goal is to not crash on messy input and to clearly understand why a command didn’t parse.
First, clean the input and split into tokens:
fun splitTokens(line: String): List<String> {
return line.trim()
.split(" ")
.filter { it.isNotEmpty() }
}
Check:
fun main() {
val tokens = splitTokens(" add amount=120 category=food ")
println(tokens) // [add, amount=120, category=food]
}
Next, safely get the command and arguments. Important: tokens[0] is dangerous if the list is empty. So we check isEmpty() first.
fun main() {
val line = readln().trim()
val tokens = splitTokens(line)
if (tokens.isEmpty()) {
println("Empty command. Enter something.")
return
}
val command = tokens[0].lowercase()
val args = tokens.drop(1)
println("command=$command, args=$args")
}
We use readln() as the primary input method in console programs.
Parsing key=value arguments into a Map
Now we’ll take the next step: process the token list after the add command and try to extract amount, category, note.
We’ll write a function that walks through tokens and builds a Map<String, String> from valid key=value pairs. We already know Map and that map[key] can return null, so this also fits our safe programming style.
fun parseArgs(tokens: List<String>): Map<String, String> {
val result = mutableMapOf<String, String>()
for (t in tokens) {
val kv = parseKeyValue(t) ?: continue
val (k, v) = kv
result[k] = v
}
return result
}
Check:
fun main() {
val args = parseArgs(listOf("amount=120", "category=food", "oops", "note=coffee"))
println(args) // {amount=120, category=food, note=coffee}
}
Notice that we chose a strategy: if a token is “bad” ("oops"), we skip it. We could return an error instead, but that’s a different strategy. Today we care about robustness and simplicity.
Final mini-scenario: add command and diagnostic messages
Now let’s put it all together: read a line, extract the command, parse arguments, check required fields.
We won’t implement full expense storage right now (that was/will be covered in other lectures). We’ll just show that parsing works and doesn’t crash.
fun main() {
val tokens = splitTokens(readln())
if (tokens.isEmpty()) {
println("Enter a command, for example: add amount=120 category=food note=coffee")
return
}
val command = tokens[0].lowercase()
val args = parseArgs(tokens.drop(1))
if (command != "add") {
println("Unknown command: $command")
return
}
val amountRaw = args["amount"]
val category = args["category"]
val note = args["note"] ?: ""
val amount = amountRaw?.toIntOrNull()
if (amount == null || category == null || category.isBlank()) {
println("Invalid input. Required: amount=<Int> and category=<text>")
return
}
println("Adding an expense: amount=$amount, category=$category, note=$note")
}
There are several important “safety mindset” points here:
- We don’t assume the command exists.
- We don’t assume amount and category were provided.
- We don’t assume amount is a number (we use toIntOrNull()).
- We don’t slice strings by indexes without checks, because we moved that into parseKeyValue.
8. Typical mistakes when parsing strings
Mistake #1: using the result of indexOf as if it’s always valid.
Most often it looks like this: val i = s.indexOf('='); val left = s.substring(0, i). On “correct” strings everything works, but on a string without '=' you get an exception. The fix is one habit: always check indexOf, because -1 is the normal “not found” answer.
Mistake #2: mixing up substring(start, end) boundaries and expecting an inclusive end.
This is a classic because the brain likes “inclusive.” In Kotlin, end is excluded. If you slice “up to the delimiter,” then substring(0, eq) already excludes the '=' character itself, which is convenient. But trying to “include the last character” often leads to end = length + 1 and a crash.
Mistake #3: slicing an empty string and hoping there’s at least one character.
This appears in code like substring(0, 1) without checks. On empty input, that’s a crash. In robust code, you either check isNotEmpty(), or structure the logic so the empty string is handled by a separate branch (for example, “ask to re-enter input”).
Mistake #4: doing split(" ") and believing that “extra spaces won’t matter.”
They do. Multiple spaces produce empty tokens, which then unexpectedly break argument parsing. The pattern “trim() → split(" ") → filter { it.isNotEmpty() }” makes behavior predictable and eliminates weird bugs that look like “sometimes it works, sometimes it doesn’t.”
Mistake #5: trying to “slice no matter what” instead of choosing an error strategy.
Sometimes you want to write: “well, the user should enter it correctly.” But practice shows the opposite: the user enters whatever they manage. So you need to decide in advance: on error, do we return null, return a default, or print a diagnostic message and ask to try again. The key is that behavior should be explicit, not “it just kinda happened.”
GO TO FULL VERSION