Removing all whitespaces from a string :
Kotlin doesn’t provide any string method to remove all whitespaces from a string. The only way to do it by replacing all blank spaces with an empty string.
The easiest way to do this is by using regex. \s regex matches all whitespaces in a string. We will use the replace method of string to replace these whitespaces with an empty string.
Kotlin program :
The below kotlin program removes all whitespaces from the givenString:
fun main() {
val givenString = " The quick brown fox jumps over the lazy dog "
print(givenString.replace("\\s".toRegex(),""))
}
It will print the below output :
Thequickbrownfoxjumpsoverthelazydog
Similar tutorials :
- Kotlin tutorial : String in Kotlin with examples
- Kotlin program to change uppercase and lowercase of a string
- Kotlin String template : Explanation with Examples
- Kotlin program to reverse a string recursively
- Kotlin program to print each character of a string (4 different ways)
- Kotlin program to access a character in a string by index