In this tutorial, you shall learn how to replace all the occurrences of a specific character in a given string in Kotlin, using String.replace() function, with examples.

Kotlin – Replace specific character in String

To replace all the occurrences of a specific character with another character in a string in Kotlin, you can use String.replace() function.

Call the replace() function on the string, and pass the old character, and new replacement character as arguments. The function returns a new string with the contents of the original string, where the search character is replaced with a new character.

Syntax

If str is the given string, then the syntax of the statement to replace a search character oldChar with new character newChar is

str = str.replace(oldChar, newChar)

Please provide the characters as string values to the replace() function.

ADVERTISEMENT

Examples

In the following program, we take a string in str, replace the character l with the character m in the string.

Main.kt

fun main() {
    var str = "helloworld"
    val oldChar = "l"
    val newChar = "m"
    str = str.replace(oldChar, newChar)
    println(str)
}

Output

hemmowormd

If you would like the replacement operation to ignore the case of character, we can pass true for the ignoreCase parameter to replace() function.

Main.kt

fun main() {
    var str = "helLoworLd"
    val oldChar = "l"
    val newChar = "m"
    str = str.replace(oldChar, newChar, ignoreCase = true)
    println(str)
}

Output

hemmowormd

Conclusion

In this Kotlin Tutorial, we learned how to replace specific character with a new character in a string using String.replace() function.