1. Overview
In this article, we will learn to remove all spaces from a Kotlin String.
2. Kotlin String
The String
class is immutable that represents character strings. Usually, a string value is a sequence of characters enclosed in double-quotes ("
). All string literals in Kotlin code, such as "abc"
, are implemented as instances of this class.
3. Kotlin remove spaces from String
Let’s see different ways to remove space from the String.
All the below solutions remove all white space characters including tab \t, new line \n.
3.1. Use the filter to remove spaces
You can use the filter
function to remove white spaces from the String.
It returns a char sequence containing only those characters from the original string that matches the provided predicate.
Here, you can check if the character is a white space character using the isWhitespace
function.
var str = "This is an example text".filter { !it.isWhitespace() }
3.2 filterNot to remove spaces in String
Alternatively, you can remove white space by using filterNot
function.
This function returns a character sequence containing only those characters from the original string that does not match the provided predicate.
For example, the following code checks whether the string has a white space character and filter only non-whitespace characters.
val string = "This is an example text".filterNot { it.isWhitespace() }
3.3. Kotlin String replace
You can use String replace function to replace the white space character.
"This is an example text".replace("\\s".toRegex(), "")
3.4. Kotlin extension function to remove spaces
You can create an extension function to remove spaces from the string.
fun main() { var str = "This\t is an example text".removeWhitespaces() println(str) } fun String.removeWhitespaces() = filter{ !it.isWhitespace()}
4. Conclusion
To sum up, we have learned to remove all white spaces from a Kotlin String. You can find code samples in our GitHub repository.