To remove special characters from a string in Kotlin, you can use the replace
method with a regular expression.
In this example,
str
with a value containing special characters.replace
method on str
with a regular expression that matches any non-alphanumeric character.replace
method replaces all matches of the regular expression with an empty string.fun main() {
val str = "Hello, World! Welcome to Kotlin@2024."
val cleanStr = str.replace(Regex("[^A-Za-z0-9 ]"), "")
println("Original String: $str")
println("Cleaned String: $cleanStr")
}
Original String: Hello, World! Welcome to Kotlin@2024. Cleaned String: Hello World Welcome to Kotlin2024
In this example,
input
with a value containing various special characters.replace
method on input
with a regular expression that matches any character that is not a letter or a digit.replace
method removes all such characters, leaving only alphanumeric characters and spaces.fun main() {
val input = "Kotlin#1! Developer$%@"
val output = input.replace(Regex("[^A-Za-z0-9 ]"), "")
println("Original Input: $input")
println("Cleaned Output: $output")
}
Original Input: Kotlin#1! Developer$%@ Cleaned Output: Kotlin1 Developer
In this tutorial, we learned How to Remove Special Characters from a String in Kotlin language with well detailed examples.