Kotlin: String split, trim, substring

Substring

1 .substringAfter(delimiter: String, missingDelimiterValue: String = this) Method

You want to get a substring using a defined delimiter parameter. The result you get is the substring after the first appearance of delimiter. If the source string does not contain the delimiter, then the missingDelimeterValue will be returned which defaults to the source string.

2 .substringBefore(delimiter: String, missingDelimiterValue : String = this) Method

Above, in the last method, I mention how we can get the substring after the first appearance of delimiter. Well, with this method we can get the substring before the first appearance of delimiter.

3.substringAfterLast(delimiter : String, missingDelimiterValue : String= this) Method

the name of this method had a similarity to substringAfter but it works a little different . So, this substring method starts finding the delimiter value from the right side of the source string and returns a substring after the last occurrence of delimiter.

Assuming a file path which contains the two same delimeter and I only want to get the substring after the last delimiter then this method is perfect for our logic.

3 .substringBeforeLast(delimiter: String, missingDelimiterValue : String= this) Method

Difference between this substring method and previous: this method returns the substring before the last occurrence of the delimiter. The method also starts searching from the right-side and when it finds the first delimiter it returns the left-sided substring which not even used for searching.

Try implementing this in different cases.

val value = st!!.trim().substringBefore(" ").toDoubleOrNull()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ajay Deepak

Ajay Deepak

Product Manager, life coach, NLP practitioner