Split a string on whitespace in Kotlin
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val str = "A B" val words = str.split("\\s".toRegex()).toTypedArray() println(words.contentToString()) // [A, B] } |
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}.
|
1 2 3 4 5 6 7 8 |
fun main() { val str = "A B" val words = str.split("\\p{Space}".toRegex()).toTypedArray() println(words.contentToString()) // [A, B] } |
If you need to group the adjacent whitespaces as a single delimiter, use the greedy quantifier '\s+' where + represents one or more times.
|
1 2 3 4 5 6 7 8 |
fun main() { val str = "A B" val words = str.split("\\s+".toRegex()).toTypedArray() println(words.contentToString()) // [A, B] } |
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val str = " A B" val words = str.trim().split("\\s+".toRegex()).toTypedArray() println(words.contentToString()) // [A, B] } |
If the regular expression is frequently called, better compile the regular expression to get a performance boost:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.regex.Pattern private val WHITESPACE = Pattern.compile("\\s+") fun main() { val str = " A B" val words = WHITESPACE.split(str.trim()) println(words.contentToString()) // [A, B] } |
That’s all about splitting a string on whitespace in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)