How to replace duplicate whitespaces in a String in Kotlin?

In order to remove extra whitespaces in a string, we will use the replace() function along with toRegex() function from the String class. To replace all the consecutive whitespaces with a single space " ", use the replace() function with the regular expression "\s+" which matches with one or more whitespace characters.

Example – Removing extra whitespaces in Kotlin

Take a look at the following example −

fun main(args: Array<String>) {
   var myString = "Removing ex tra spa ce from String"
   println("Input String: <br>" + myString)

   // removing duplicate whitespace
   println("\nExtra whitespaces removed: <br>"
   + myString.replace("\s+".toRegex(), " "))

   // removing all the whitespaces
   println("\nAfter removing all the whitespaces: <br>"
   + myString.replace("\s+".toRegex(), ""))
}

Output

It will generate the following output −

Input String:
Removing ex tra spa ce from String

Extra whitespaces removed:
Removing ex tra spa ce from String

After removing all the whitespaces:
RemovingextraspacefromString

You can use the use the regular expression "\s{2,}" which matches with exactly two or more whitespace characters.

fun main(args: Array<String>) {
   var myString = "Use Coding Ground to Compile and Execute Kotlin Codes"
   println("Input String: <br>" + myString)

   // removing consecutive double whitespaces
   println("\nAfter removing double whitespaces: <br>"
   + myString.replace("\s{2,}".toRegex(), " "))
}

Output

It will pick consecutive whitespaces in the given string and replace them with single whitespaces.

Input String:
Use Coding Ground to Compile and Execute Kotlin Codes

After removing double whitespaces:
Use Coding Ground to Compile and Execute Kotlin Codes
Updated on: 2022-03-16T13:47:34+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements