In this tutorial, you shall learn how to split a given string by one or more adjacent spaces as delimiter in Kotlin, using String.split() function and regular expression, with examples.

Kotlin – Split string by one or more spaces

To split a string by one or more spaces as separator in Kotlin, you can use String.split() function with regular expression.

Call split() function on the string, and pass the regular expression that matches one or more whitespaces "\\s+".toRegex(), as argument to the function.

Syntax

If str is the given string, then the syntax to split this string by one or more whitespaces is

</>
Copy
str.split("\\s+".toRegex())

Examples

1. Split string by one or more spaces using split()

In the following program, we take a string in str, and split this string to parts by one or more spaces as separator, using String.split() function.

Main.kt

</>
Copy
fun main() {
    val str = "hello    world  how are   you"
    val parts = str.split("\\s+".toRegex())
    println(parts)
}

Output

[hello, world, how, are, you]

2. Trim before splitting the string

If there are any leading or trailing spaces in the string, we may get an empty string in the split parts as shown in the following program.

Main.kt

</>
Copy
fun main() {
    val str = "   hello    world  how are   you   "
    val parts = str.split("\\s+".toRegex())
    println(parts)
}

Output

[, hello, world, how, are, you, ]

If you do not want empty strings in your output, trim the input string before splitting as shown in the following program.

Main.kt

</>
Copy
fun main() {
    val str = "   hello    world  how are   you   "
    val parts = str.trim().split("\\s+".toRegex())
    println(parts)
}

Output

[hello, world, how, are, you]

Conclusion

In this Kotlin Tutorial, we learned how to split a string by one or more spaces as separator using String.split() function.