How to replace duplicate whitespaces in a String in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

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: 
" + myString)    // removing duplicate whitespace    println("
Extra whitespaces removed:
"    + myString.replace("\s+".toRegex(), " "))    // removing all the whitespaces    println("
After removing all the whitespaces:
"    + 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: 
" + myString)    // removing consecutive double whitespaces    println("
After removing double whitespaces:
"    + 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
raja
Updated on 16-Mar-2022 13:47:34

Advertisements