In this tutorial, you shall learn how to split a given string by comma character as separator in Kotlin, using String.split() function, with the help of examples.

Kotlin – Split string by comma

To split a string by comma character as separator in Kotlin, you can use String.split() function.

Call split() function on the string, and pass the comma 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 comma character, then the syntax to split this string into a list of values is

</>
Copy
str.split(',')

Examples

1. Split values in string separated by comma

In the following program, we take a string in str, and split this string into parts with comma character as separator, using String.split() function.

Main.kt

</>
Copy
fun main() {
    val str = "apple,banana,cherry,mango"
    val parts = str.split(' ')
    println(parts)
}

Output

[apple, banana, cherry, mango]

Related Tutorials

Conclusion

In this Kotlin Tutorial, we learned how to split a string by a single space character as separator using String.split() function.