Kotlin在最后一个空格中拆分字符串

Kotlin在最后一个空格中拆分字符串,kotlin,Kotlin,我有一根绳子,我想把它分开,去掉最后一部分 例如,类似于此输入的内容: var example = "Long string to split in the last space" 我想达到这个结果 var result = "Long string to split in the last" 使用: 使用删除最后一个n单词的更详细的替代方法: var example = "Long string to split in the last space" var result = exampl

我有一根绳子,我想把它分开,去掉最后一部分

例如,类似于此输入的内容:

var example = "Long string to split in the last space"
我想达到这个结果

var result = "Long string to split in the last"
使用:


使用删除最后一个
n
单词的更详细的替代方法:

var example = "Long string to split in the last space"
var result = example.split(" ")
                    .dropLast(1)
                    .joinToString(" ")
println(result) // Long string to split in the last

“不仅更加冗长,而且要慢得多。@阿列克谢·罗曼诺夫,你会建议我删除我的答案吗,这样我就不会让搜索者感到困惑了?”?我只是认为substringBeforeLast无法删除最后的
n
单词。这可能是这个问题的一个常见延伸。我不会,因为缺点很明显。我其实没注意到你提到最后n个字。
var example = "Long string to split in the last space"
var result = example.split(" ")
                    .dropLast(1)
                    .joinToString(" ")
println(result) // Long string to split in the last