Remove given characters from a string in Kotlin
This article explores different ways to remove given characters from a string in Kotlin.
The replace() function replaces each substring of a string that matches the given regular expression. It can be used to return a new string without the specified characters (since strings are immutable). For instance, consider the following code that will replace all matches of the regular expression \w with an empty string. Here, \w matches with the word character set [a-zA-Z_0-9].
|
1 2 3 4 5 6 7 |
fun main() { var str = "Kotlin_1.5!!" str = str.replace("[^\\w+]".toRegex(), "") println(str) // Kotlin_15 } |
We can retain specific characters using negation ^. For example, [^a-zA-Z] matches with all characters except ASCII alphabets.
|
1 2 3 4 5 6 7 |
fun main() { var str = "Kotlin_1.5!!" str = str.replace("[^a-zA-Z]".toRegex(), "") println(str) // Kotlin } |
Here’s another variation that uses the overloaded version of the replace() function to remove all occurrences of the specified characters from the string.
|
1 2 3 4 5 6 7 8 |
fun main() { var str = "Kotlin_1.5!!" val charsToRemove = "_!" charsToRemove.forEach { str = str.replace(it.toString(), "") } println(str) // Kotlin1.5 } |
That’s all about removing given characters from a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)