Kotlin function for getting start and end index of substring

Viewed 1895

I'm wondering is there some method or methods combo that could obtain these results.

What I meant is that you have a string ex. "Hello world, how are you?" And I want to achieve following functionality, to get start and end index of substring in that string.

ex. substring = "world", and start index would be 6, and end index 10

Is there something like this in standard kotlin libraries?

2 Answers

Something like this?

val s = "Hi there"
val substringToFind = "there"

val start = s.indexOf(substringToFind)
val end = start + substringToFind.length

println(s.substring(start,end))

output: there

Maybe you could just use indexOf assuming you just want the first occurence:

fun main(args: Array<String>) {
    val str = "Hello world, how are you?"
    val sub = "world"
    println(getStartAndEndOfSubstring(str, sub))
}

fun getStartAndEndOfSubstring(str: String, sub: String): Pair<Int, Int> {
    val start = str.indexOf(sub)
    when (start != -1) {
        true -> return Pair(start, start + sub.length - 1)
        false -> return Pair(-1, -1)
    }
}

Output:

(6, 10)
Related