Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin split string in the last space

Tags:

kotlin

I have a String and i want to split it , and drop the last part .

For example something like that for this input :

var example = "Long string to split in the last space"

I want to achieve this result

var result = "Long string to split in the last"
like image 431
dddddrrrrrr Avatar asked Oct 15 '25 14:10

dddddrrrrrr


2 Answers

Use substringBeforeLast:

"Long string to split in the last space".substringBeforeLast(" ")
like image 96
awesoon Avatar answered Oct 18 '25 18:10

awesoon


A more verbose alternative to substringBeforeLast that works for removing the last n words by using dropLast:

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
like image 23
Sash Sinha Avatar answered Oct 18 '25 19:10

Sash Sinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!