Start learning free

LESSON 63 OF 677 · STRINGS I

String Replace in Kotlin

Lesson

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

s.replace(oldValue, newValue)       // replaces all occurrences
s.replaceFirst(oldValue, newValue)  // replaces only the first occurrence

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