Comprehension

Report a typo

Here's an example function that takes in a CharSequence and a list of Char objects and returns the index of the first character in the list that appears in the input sequence, or -1 if no such character is found in the list:

fun findFirstIndex(charSequence: CharSequence, charsToFind: List<Char>): Int {
    for (charIndex in charSequence.indices) {
        val currentChar = charSequence[charIndex]
        if (currentChar in charsToFind) {
            return charIndex
        }
    }
    return -1
}

Here's an example usage of the function:

fun main() {
    val charSequence = "This is a sample string"
    val charsToFind = listOf('x', 'z', 'm', 's')
    val firstIndex = findFirstIndex(charSequence, charsToFind)
    println("The first index is: $firstIndex")
}

What does the program print?

Enter a short text
___

Create a free account to access the full topic