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

Kotlin – Remove specific character in String

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

Call the replace() function on the string and pass the character (as string) to be removed, and an empty string as new replacement character, as arguments. The function returns a new string with the contents of the original string, where the search character is removed.

Syntax

If str is the given string, then the syntax of the statement to remove a specific character ch is

</>
Copy
str = str.replace(ch, "")

Please provide the character ch as string value to the replace() function.

Examples

In the following program, we take a string in str, remove the character l from the string.

Main.kt

</>
Copy
fun main() {
    var str = "helLoworLd"
    val ch = "l"
    str = str.replace(ch, "")
    println(str)
}

Output

heoword

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

</>
Copy
fun main() {
    var str = "HelLoWorLd"
    val ch = "l"
    str = str.replace(ch, "", ignoreCase = true)
    println(str)
}

Output

HeoWord

Conclusion

In this Kotlin Tutorial, we learned how to remove all the occurrences of a specific character in a string using String.replace() function.