1. Overview

Removing whitespaces from strings is a common task in software development, and many programming languages have great built-in support that helps solve the problem.

In this tutorial, we’ll see some techniques to remove whitespaces from strings with Kotlin.

2. The replace Method

Using the native method replace() method, we can remove any character that matches the empty string:

val example = "House Of The Dragon"
val withOutSpaces = example.replace(" ", "")


We can also define a regular expression to pass to the replace method:

val example = "House Of The Dragon"
val withOutSpaces = example.replace("\\s".toRegex(), "")


Sometimes, whitespace characters can be non-standard. There are several Unicode characters that come across as whitespace that other, simpler replacement mechanisms may not handle well. To address this issue, we can define a regular expression that matches these Unicode whitespace characters:

val example = "House Of The Dragon"
val withOutSpaces = example.replace("\\p{Zs}+".toRegex(), "")


3. Character Filtering

We can also take advantage of filtering support for strings to test individual characters. There’s a built-in function to determine if a Char is a whitespace character – isWhitespace(). We can put these together to solve the problem:

val example = "House Of The Dragon"
val withOutSpaces = example.filterNot { it.isWhitespace() }


4. Variations on the trim Method

Sometimes, we need to delete whitespace only at the beginning or end of the string. The trim() method and its variations can help us perform this task:

val example = " House Of The Dragon "
val trimmed = example.trim()

assertThat(trimmed).isEqualTo("House Of The Dragon")

Similarly, we can remove whitespace at just the start or end of the string:

val example = "  House Of The Dragon  "
val trimmedAtStart = example.trimStart()
val trimmedAtEnd = example.trimEnd()

assertThat(trimmedAtStart).isEqualTo("House Of The Dragon  ")
assertThat(trimmedAtEnd).isEqualTo("  House Of The Dragon")

5. Conclusion

In this tutorial, we’ve explored some techniques for removing all whitespace characters from strings. We also saw how to remove whitespaces at the beginning or end of a string with variations on the trim() function.

As always, the complete code for this article is available over on GitHub.

Comments are closed on this article!