Split string by underscore in Kotlin
To split a given string by underscore as delimiter in Kotlin, call split() function on the given string and pass the "_" delimiter string as argument.
str.split("_")
The following is a simple use case where we take a string with values separated by underscore. And split the string by the underscore delimiter.
apple_banana_cherry_mango
_ _ _ <- delimiter positions
apple banana cherry mango <- split values
Examples
Split string by underscore separator
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 values = str.split("_")
for (value in values) {
println(value)
}
}
Output
apple
banana
cherry
mango