Kotlin – Replace multiple spaces with a single space in a String

Replace multiple spaces with a single space in Kotlin

To replace multiple spaces with a single space in a given string in Kotlin, you can use regular expression along with the String.replace() function.

The syntax of the replace() function to replace multiple consecutive spaces with a single space is

str.replace("\\s+".toRegex(), " ")

where "\\s+".toRegex() matches one or more consecutive spaces, and are replaces with a new value of single space " ".

Examples

Replace multiple spaces with a single space in an article

Consider a scenario where we are given an article to be published in a newspaper as a string value. But there are places where there are multiple consecutive spaces instead of one space.

We shall use String.replace() function as mentioned above, to clean the article.

Kotlin Program

fun main() {
    val str = "Hello readers!    Welcome to   the  new  world."
    val result = str.replace("\\s+".toRegex(), " ")
    println(result)
}

Output

Hello readers! Welcome to the new world.