Kotlin – Split String by Single Space

Split string by single space character in Kotlin

To split a given string by single space delimiter in Kotlin, call split() function on the given string and pass the single space " " delimiter string as argument.

str.split(" ")

The following is a simple use case where we take a string with values separated by single space character. And split the string by comma delimiter.

apple banana cherry mango
     _      _      _       <- delimiter positions

Examples

Split string by single space

In the following program, we take a string in str and split this string into values where values in the string are separated by a single space " ".

Kotlin Program

fun main() {
    val str = "apple banana cherry mango"
    val values = str.split(" ")
    for (value in values) {
        println(value)
    }
}

Output

apple
banana
cherry
mango