Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: split string from end

Tags:

kotlin

I want to split I_have_a_string into I_have_a and string.

Is there a built in function to split from end in Kotlin? The following is what I am doing now:

val words = myString.split("_")
val first = words.dropLast(1).joinToString("_")
val second = words.last()
like image 745
Jack Guo Avatar asked Jul 17 '26 08:07

Jack Guo


1 Answers

substringBeforeLast() and substringAfterLast() are Kotlin built in functions very convenient for this case:

"I_have_a_string".substringBeforeLast("_") // output: "I_have_a"
"I_have_a_string".substringAfterLast("_") // output: "string"