Start learning free

LESSON 62 OF 348 · STRINGS I

String Replace in Kotlin: replace and replaceFirst

Lesson Read the full explanation

In Java, you can replace part of a string using the replace() method:

s.replace(oldValue, newValue)       // replaces all occurrences
s.replaceFirst(regex, replacement)  // replaces first match

Here are some examples:

val sentence = "I love cats"
val result = sentence.replace("cats", "dogs")
println(result)  // "I love dogs"

val text = "aaa"
println(text.replace("a", "b"))  // "bbb"

replace() returns a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign it to result.

STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · STRINGS I

    String Replace in Kotlin, explained

    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".

    1. Call replace on sentence. The first argument is the text to look for, "cats". The second is what goes in its place, "dogs".
    2. Store the new string in result. It is declared with val because 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 leaves sentence as it was.
    • Expecting one replacement. replace changes every match. Reach for replaceFirst when 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 unless ignoreCase = true.
    • Assigning to a val twice. If you want to reassign sentence itself, declare it with var.

    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 Regex for patterns.
    • The original string never changes, so keep the result.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free