Kotlin: String split, trim, substring

Ajay Deepak
2 min readJun 13, 2020
  1. If you are certain that the number is always at the start, then use split() with space as delimiter and from the returned list take the 1st item and parse it to Double:
    val value = st!!.split(" ")[0].toDoubleOrNull()
  2. If there is a case of spaces at the start or in between, use this:
    val value = st!!.trim().split("\\s+".toRegex())[0].toDoubleOrNull()
  3. And another way with substringBefore(): Returns a substring before the first occurrence of delimiter. If the string does not contain the delimiter, returns missingDelimiterValue which defaults to the original string.
    val value = st!!.trim().substringBefore(" ").toDoubleOrNull()
  4. if there is only 1 integer number in the string, remove every non numeric char with replace():
    val value = st!!.replace("\\D".toRegex(), "").toDoubleOrNull()

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()

--

--