Delete specific character in String in Kotlin
To delete all the occurrences of a specific character in a given string in Kotlin, you can use String.replace()
function.
Call replace()
function on the given String object str
, and pass the specified character to be deleted, and an empty string as arguments.
str.replace(charToDelete.toString(), "")
replace()
function returns a new string with all the occurrence of specified character replaced with empty string, in the given string.
Note: We have converted the character to string using toString()
because replace()
function takes only a string as first argument, but not character.
Examples
Delete the character ‘p’ from the string
In the following program, we take a string value in str
, and delete the character 'p'
from the string.
Kotlin Program
fun main() {
val str = "apple"
val charToDelete = 'p'
val resultString = str.replace(charToDelete.toString(), "")
println(resultString)
}
Output
ale