Kotlin:从末尾分割字符串

JGu*_*Guo 6 kotlin

我想I_have_a_string分成I_have_astring

Kotlin 中是否有内置函数可以从末尾拆分?以下是我现在正在做的事情:

val words = myString.split("_")
val first = words.dropLast(1).joinToString("_")
val second = words.last()
Run Code Online (Sandbox Code Playgroud)

小智 10

substringBeforeLast()substringAfterLast()是 Kotlin 内置函数,对于这种情况非常方便:

"I_have_a_string".substringBeforeLast("_") // output: "I_have_a"
"I_have_a_string".substringAfterLast("_") // output: "string"
Run Code Online (Sandbox Code Playgroud)