This article explores different ways to split a string on whitespace in Kotlin. The whitespace characters consist of ' ', '\t', '\n', '\r', 'f', etc.

We can use the split() function to split a char sequence around matches of a regular expression. To split on whitespace characters, we can use the regex '\s' that denotes a whitespace character.

Download Code

 
Note that we have called the toTypedArray() function, since the split() function returns a list. Here’s an equivalent version using POSIX character class \p{Space}.

Download Code

 
If you need to group the adjacent whitespaces as a single delimiter, use the greedy quantifier '\s+' where + represents one or more times.

Download Code

 
All the above solutions don’t remove the leading or trailing spaces from a String. To handle it, we can trim the string before calling the split() function.

Download Code

 
If the regular expression is frequently called, better compile the regular expression to get a performance boost:

Download Code

That’s all about splitting a string on whitespace in Kotlin.