To keep only alphabets in a string in Kotlin, you can use the replace() function with a regular expression that matches non-alphabetic characters and replaces them with an empty string.
In this example,
str1
with a value of "Hello123 World"
.replace()
function with a regular expression "[^a-zA-Z]"
to replace non-alphabetic characters with an empty string.str1
.fun main() {
var str1 = "Hello123 World"
str1 = str1.replace("[^a-zA-Z]".toRegex(), "")
println("Modified string: $str1")
}
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.replace()
function with a regular expression "[^a-zA-Z]"
to replace non-alphabetic characters with an empty string.str2
.fun main() {
var str2 = "apple@banana"
str2 = str2.replace("[^a-zA-Z]".toRegex(), "")
println("Modified string: $str2")
}
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in Kotlin language with well detailed examples.