In this tutorial, you shall learn how to split a given string by single space character as delimiter in Kotlin, using String.split() function, with examples.
Kotlin – Split string by single space character
To split a string by single space character as separator in Kotlin, you can use String.split() function.
Call split() function on the string, and pass the single space character ' '
, as argument to the function. The function returns a list of split parts.
Syntax
If str
is the given string and the values in it are separated by space character, then the syntax to split this string into a list of values is
str.split(' ')
Examples
1. Split values in string separated by single space
In the following program, we take a string in str
, and split this string into parts with single space character as separator, using String.split() function.
Main.kt
fun main() {
val str = "apple banana cherry mango"
val parts = str.split(' ')
println(parts)
}
Output
[apple, banana, cherry, mango]
Related Tutorials
- Kotlin – Split string by any number of whitespace characters
- Kotlin – Split string by any whitespace character
Conclusion
In this Kotlin Tutorial, we learned how to split a string by a single space character as separator using String.split() function.