Kotlin – Split String

Split String in Kotlin

To split a string by a given separator or delimiter in Kotlin, you can use String.split() function.

apple, banana, cherry, mango
     --      --      --       <- delimiter positions
apple  banana  cherry  mango  <- split values

Call split() function on the string str, and pass the delimiter string as argument.

str.split(delimiter)

The functions splits the string at delimiter occurrences, and returns a List of strings.

Examples

Split string by “, “

In the following program, we take a string value in str where values in the string are separated by the delimiter string ", ". We shall split this string into a list of values. Then we use a For loop to iterate over the split values.

Kotlin Program

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

Output

apple
banana
cherry
mango

Split string by underscore

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

Kotlin Program

fun main() {
    val str = "apple_banana_cherry_mango"
    val delimiter = "_"
    val values = str.split(delimiter)
    for (value in values) {
        println(value)
    }
}

Output

apple
banana
cherry
mango