Home > OS >  Kotlin - Way to get a substring starting from a specified index until another specified index or end
Kotlin - Way to get a substring starting from a specified index until another specified index or end

Time:10-20

Example

val string = "Large mountain"

I would like to get a substring starting from the index of the "t" character until index of "t" 7 with the 7 being arbitrary or end of string.

val substring = "tain"

Assuming that the string is larger

val string2 = "Large mountain and lake"

I would like to return

val substring2 = "tain and l"

If my I were to try to substring(indexOf("t") ,(indexOf("t") 7) )

In this second case right now if I use "Large mountain" I would get an index out of bounds exception.

CodePudding user response:

There's a method called substring for this. Use it like so:

val str = "Large mountain"
val subStr = str.substring(10, str.length)
print(subStr)  // "tain"

Index 10 is when the letter 't' appears, the str.length is the end index, in this case, the end of the string.

Method documentation here.

CodePudding user response:

I don't think there's an especially elegant way to do this.

One fairly short and readable way is:

val substring = string.drop(string.indexOf('t')).take(7)

This uses indexOf to locate the first 't' in the string, and thendrop() to drop all the previous characters, and take() to take (up to) 7 characters from there.

However, it creates a couple of temporary strings, and will give an IllegalArgumentException if there's no 't' in the string.

Improving robustness and efficiency takes more code, e.g.:

val substring = string.indexOf('t').let {
    if (it >= 0)
        string.substring(it, min(it   7, string.length))
    else
        string
}

That version lets you specify exactly what you want if there's no 't' (in the else branch); it also avoids creating any temporary objects. As before, it uses indexOf() to locate the first 't', but then uses min() to work out how long the substring can be, and substring() to generate it.

If you were doing this a lot, you could of course put it into your own function, e.g.:

fun String.substringFrom(char: Char, maxLen: Int) = indexOf(char).let {
    if (it >= 0)
        substring(it, min(it   maxLen, length))
    else
        this
}

which you could then call with e.g. "Large mountain".substringFrom('t', 7)

  • Related