Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin String replace including delimiter

Tags:

kotlin

I have a common pattern where I want to operate on a string like abckey123 where I want to clear the string before key but also remove the key.

Is there a commonly accepted way to do this? Or even better a way to make this a single method call on all string objects?

Ideas:

item.replaceBefore("key", "").replace("key", "")
item.split("key").last()
like image 985
Milk Avatar asked Sep 08 '26 23:09

Milk


1 Answers

If you want to get all text after the "key" substring, you can use substringAfter function:

val result = item.substringAfter("key")

The second parameter of this function allows to specify what to return if the delimiter is not found. By default it returns the entire string, but you can pass an empty string for example:

val result = item.substringAfter("key", "")
like image 92
Ilya Avatar answered Sep 12 '26 21:09

Ilya



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!