dddddrrrrrr
dddddrrrrrr

Reputation: 317

Kotlin split string in the last space

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"

Upvotes: 4

Views: 1216

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22360

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

Upvotes: 2

awesoon
awesoon

Reputation: 33651

Use substringBeforeLast:

"Long string to split in the last space".substringBeforeLast(" ")

Upvotes: 12

Related Questions