1. Overview

We may need to remove characters from our strings. We should note that Strings are immutable in Kotlin, so to remove a character from the string, we’re actually creating a new one.

In this short tutorial, we’ll look at a few methods for removing a character from a string in Kotlin.

2. Using replace

A String is a sequence of characters. We can use the replace extension function to blank out a specific character in a string. It returns a new string with all occurrences of the old character removed:

val string = "Ba.eldung"
assertEquals("Baeldung", string.replace(".", ""))

3. Using Filtering

Let’s try another extension function. The function filterNot returns a string containing only those characters that don’t match a predicate:

val string = "Ba.eldung"
assertEquals("Baeldung", string.filterNot { it == '.' })

4. Using deleteAt

The next way to remove a single character from the string is to use StringBuilder.

Firstly, we pass our string to the StringBuilder constructor. Then, we can use the deleteAt method, which removes the character at the specified index from this StringBuilder. After that, we can obtain a new String by using the toString function:

val string = "Ba.eldung"
val stringBuilder = StringBuilder(string)
assertEquals("Baeldung", stringBuilder.deleteAt(2).toString())

5. Using removeRange

removeRange is another useful extension function. It removes the part of the String at a given range. This range is exclusive, so it doesn’t remove the character at the second index provided:

val string = "Ba.eldung"
assertEquals("Baeldung", string.removeRange(2, 3))

6. Using removeSuffix and removePrefix

In Kotlin, there are few convenient functions for operating on strings. If we want to remove only the beginning of the string, we can use the removePrefix function. If a string starts with the given prefix, the function returns a copy of this string with the prefix removed. Otherwise, it returns the original:

val string = "Baeldung"
assertEquals("aeldung", string.removePrefix("B"))
assertEquals("Baeldung", string.removePrefix("Z"))

For removing the end of the String, we can use removeSuffix. If a string ends with the given suffix it returns a copy of this string with the suffix removed:

val string = "Baeldung"
assertEquals("Baeldun", string.removeSuffix("g"))
assertEquals("Baeldung", string.removeSuffix("Z"))

7. Conclusion

In this article, we’ve seen the most common ways to remove a character from a string in Kotlin.

As usual, the example code is available over on GitHub.

Comments are closed on this article!