Introduction :
In this tutorial, we will learn how to remove all special characters from a string in Kotlin. Our program will remove all non-alphanumeric characters excluding space. For example, if the string is abc 123 *&^, it will print abc 123.
I will show two different ways to solve it in Kotlin. Just try to run the sample programs with different strings.
Method 1: Using regex :
regex or regular expression is a sequence of characters or patterns used to match characters in a string. We can use the below regular expression :
[^A-Za-z0-9 ]
It will match all characters that are not in between A to Z and not in between a to z and not in between 0 to 9 and not a blank space. Then we will replace those characters with an empty character.
fun main() {
var str = "Hello !!!πworld @1233*@@():)πππ"
val re = "[^A-Za-z0-9 ]".toRegex()
str = re.replace(str, "")
println(str)
}
It will print the below output :
Hello world 1233
toRegex() method is used to convert one string to a regular expression. replace method is used to replace all characters matched by that regex with space.
You can also use apply:
fun main() {
var str = "Hello !!!πworld @1233*@@():)πππ"
"[^A-Za-z0-9 ]".toRegex().apply {
str = replace(str, "")
}
println(str)
}
Method 2: Using filter :
filter is another way to remove unwanted characters from a string. It takes one predicate and returns a string containing only those characters from the original string that matches the predicate. Below is the complete program :
fun main() {
var str = "Hello !!!πworld @1233*@@():)πππ"
str = str.filter { it.isLetterOrDigit() || it.isWhitespace() }
println(str)
}
We are checking if the character is a letter or digit or whitespace or not. The final result is the same as the above example.