Kotlin – Replace Substring

Replace a Substring in Kotlin

To replace a specific substring with a new replacement string in the given string in Kotlin, you can use String.replace() function.

Call replace() function on the given String object str, and pass the substring to replace oldValue, and the new replacement string newValue as arguments to the function.

str.replace(oldValue, newValue)

replace() function replaces all the occurrences of the substring oldValue with newValue. You can get the resulting string by calling toString() function on the StringBuilder object.

Examples

Validate if string contains “red”

Consider a scenario where the word "red" is misspelled in an article as "rlb". We need to use String.replace() function to replace the old value with the new old and correct the string.

Kotlin Program

fun main() {
    val str = "apple is rlb. cherry is rlb. mango is yellow."
    val oldValue = "rlb"
    val newValue = "red"

    val result = str.replace(oldValue, newValue)
    println(result)
}

Output

apple is red. cherry is red. mango is yellow.