Home > Back-end >  Obtain the length of the selected string in kotlin
Obtain the length of the selected string in kotlin

Time:11-20

I want to obtain the index chars or words in a string

for example

tv.text=" hey how are you, are you okay"

val res=tv.text.indexOf('h')

(have any way for put string instead of char?

output res=0

index of return only first char with h but in my tv text I have more h chars can we return all h chars indexs

CodePudding user response:

You can use filter function to get all the string indices with the required character.

val text = " hey how are you, are you okay"
val charToSearch = 'h'
val occurrences = text.indices.filter { text[it] == charToSearch }
println(occurences)

Try it yourself

And, if you want to search for strings instead of a single character, you can do this:

text.indices.filter { text.startsWith(stringToSearch, it) }

CodePudding user response:

The following should work (you try to find an index if you found one in the previous iteration and you begin the folloing iteration from the previously found character instance plus 1, so that you don't find the same again and again):

fun main() {
    val word = " hey how are you, are you okay"
    val character = 'h'
    var index: Int = word.indexOf(character)
    while (index >= 0) {
        println(index)
        index = word.indexOf(character, index   1)
    }
}

If you want to store the indexes for later usage you can also do the following:

fun main() {
    val word = " hey how are you, are you okay"
    val character = 'h'
    val indexes = mutableListOf<Int>()
    var index: Int = word.indexOf(character)
    while (index >= 0) {
        index = word.indexOf(character, index   1)
        indexes.add(index)
    }
    println(indexes)
}

CodePudding user response:

If you just want all the indices matching a char you can do this:

word.indices.filter { word[it] == 'h' }

Finding string matches is trickier, you could use Kotlin's regionMatches function to check if the part of the string starting at index matches what you're looking for:

val findMe = "you"
word.indices.filter { i ->
    word.regionMatches(i, findMe, 0, findMe.length)
}

You could use a regular expression too, so long as you're careful about validating the search pattern:

Regex(findMe).findAll(word)
    .map { it.range.first() } // getting the first index of each matching range
    .toList()
  • Related