Kotlin – Split string by one or more consecutive spaces

Split string by one or more consecutive spaces in Kotlin

To split a given string with one or more consecutive spaces as delimiter in Kotlin, call split() function on the given string and pass the regular expression "\\s+".toRegex() as argument.

str.split("\\s+".toRegex())

The regular expression \\s+ matches one or more consecutive spaces.

The following is a simple use case where we take a string with values separated by delimiters with variable number of consecutive spaces. And split the string at those delimiter positions.

apple     banana cherry   mango
     _____      _      ___       <- delimiter positions

Examples

Split string by one or more consecutive spaces

In the following program, we take a string in str and split this string into values where values in the string are separated by variable number of spaces

Kotlin Program

fun main() {
    val str = "apple     banana cherry   mango"
    val values = str.split("\\s+".toRegex())
    for (value in values) {
        println(value)
    }
}

Output

apple
banana
cherry
mango