Split string any whitespace in Kotlin
To split a given string by any whitespace character(s) as delimiter in Kotlin, call split()
function on the given string and pass the regular expression for whitespace pattern \\s+
as argument.
str.split("\\s+".toRegex())
The regular expression \\s+
matches any whitespace character.
The following is a simple use case where we take a string with values separated by delimiters with any number of any whitespace characters. And split the string at those delimiter positions.
apple
banana cherry mango fig
_ _ ___ _ <- delimiter positions
Examples
Split given string by any whitespace character(s)
In the following program, we take a string in str
and split this string into values where values in the string are separated by new line, tab, single space, or consecutive spaces.
Kotlin Program
fun main() {
val str = "apple\n banana\tcherry mango fig"
val values = str.split("\\s+".toRegex())
for (value in values) {
println(value)
}
}
Output
apple
banana
cherry
mango
fig