In this tutorial, you shall learn how to split a given string by any whitespace character as delimiter in Kotlin, using String.split() function and regular expression, with examples.
Kotlin – Split string by any whitespace character
To split a string by any whitespace character 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 any whitespace character "\\s".toRegex()
, as argument to the function. The function returns a list of split parts.
Syntax
If str
is the given string, then the syntax to split this string by any whitespace character is
str.split("\\s".toRegex())
Examples
1. Split string by any whitespace character
In the following program, we take a string in str
, and split this string into parts by one or more spaces as separator, using String.split() function. The string has a single space, new line, and tab. The split happens at these whitespace characters.
Main.kt
fun main() {
val str = "hello world\nhow are\tyou"
val parts = str.split("\\s".toRegex())
println(parts)
}
Output
[hello, world, how, are, you]
2. String with more than one adjacent spaces
If there are more than one spaces together, then we get an empty string at that specific split, as shown in the following program.
Main.kt
fun main() {
val str = "hello world\nhow \n\tare\tyou"
val parts = str.split("\\s".toRegex())
println(parts)
}
Output
[hello, , world, how, , , are, you]
If you do not want multiple spaces to create empty strings in your output, change the regular expression as shown in the following program
Main.kt
fun main() {
val str = "hello world\nhow \n\tare\tyou"
val parts = str.split("\\s+".toRegex())
println(parts)
}
Output
[hello, world, how, are, you]
Related Tutorials
Conclusion
In this Kotlin Tutorial, we learned how to split a string by any whitespace character as separator using String.split() function.