Replacing text
The replace function swaps every occurrence of one piece of text for another and returns the result as a new string:
val sentence = "I love cats"
val result = sentence.replace("cats", "dogs")
println(result) // I love dogs
println(sentence) // I love cats
The original is unchanged, because Kotlin strings are immutable. If you do not keep the returned string, the replacement is lost. Either store it in a new variable, as above, or assign it back to a var.
Every occurrence is replaced
With replace there is no "first match only" behaviour. All the matches are replaced:
println("aaa".replace("a", "b")) // bbb
println("I love cats and cats".replace("cats", "dogs")) // I love dogs and dogs
When you want to change only the first match, use replaceFirst:
println("cats cats".replaceFirst("cats", "dogs")) // dogs cats
Both functions take plain text, not patterns. The text is matched literally, so characters that are special in regular expressions have no special meaning here:
println("a.b.c".replace(".", "-")) // a-b-c
Every dot was replaced, which is what you would want from a literal search. If you want pattern matching, wrap the pattern in a Regex:
println("a1b22c".replace(Regex("[0-9]+"), "#")) // a#b#c
Case matters
The match is case-sensitive unless you ask otherwise. Pass ignoreCase = true by name:
println("I love CATS".replace("cats", "dogs")) // I love CATS
println("I love CATS".replace("cats", "dogs", ignoreCase = true)) // I love dogs
The first call finds nothing and returns a string equal to the original.
The exercise
The lesson starts with sentence and asks for a new val named result in which "cats" is replaced by "dogs".
- Call
replaceonsentence. The first argument is the text to look for,"cats". The second is what goes in its place,"dogs". - Store the new string in
result. It is declared withvalbecause it is assigned once.
val sentence = "I love cats"
val result = sentence.replace("cats", "dogs")
After this runs, result holds "I love dogs" and sentence still holds "I love cats".
Chaining and reassigning
Because each call returns a string, you can call another function on the result straight away. This is called chaining:
val raw = " Hello, World "
val cleaned = raw.trim().replace(" ", "_").lowercase()
println(cleaned) // hello,___world
Each step produces a new string for the next one: trim() removes the outer spaces, replace turns each remaining space into an underscore, and lowercase() changes the letters. The three spaces between the comma and World become three underscores, because every match is replaced.
If you would rather update one variable in place, declare it with var and assign the result back:
var text = "I love cats"
text = text.replace("cats", "dogs")
println(text) // I love dogs
Matches do not overlap
The search moves forward past each match it replaces. In "aaa".replace("aa", "b") the first two letters match and become b, and the remaining a has no partner, so the result is ba. When the text to find is not in the string at all, the result is simply equal to the original.
Characters work too
There is also a version that takes two characters instead of two strings: "banana".replace('a', 'o') gives bonono. Use single quotes for a Char and double quotes for a String. Mixing them, for example replace('a', "o"), does not compile.
Replacing with nothing
Passing an empty string as the replacement deletes the matches:
println("a-b-c".replace("-", "")) // abc
When replace is the wrong tool
Replacing works on text, not on positions. To change the character at a known index, you cut the string around that index with substring and join the pieces back together, or use replaceRange. And if a word appears inside a longer word, replace changes it there too: replacing "cat" in "concatenate" would alter the middle of the word. For whole-word changes, split the string into words first or use a regular expression with word boundaries.
Common mistakes
- Ignoring the return value. Writing
sentence.replace("cats", "dogs")on its own line leavessentenceas it was. - Expecting one replacement.
replacechanges every match. Reach forreplaceFirstwhen only the first should change. - Getting the argument order wrong. The old text comes first, the new text second. Reversed, the call replaces
"dogs", which is not in the sentence, and nothing happens. - Forgetting the case.
"Cats"and"cats"are different texts unlessignoreCase = true. - Assigning to a
valtwice. If you want to reassignsentenceitself, declare it withvar.
Key takeaways
s.replace(old, new)returns a new string with every match replaced.s.replaceFirst(old, new)changes only the first match.- The search text is literal; use
Regexfor patterns. - The original string never changes, so keep the result.