How to get the indexes of words from an array of strings that start with a specific letter in Kotlin

1 Answer

0 votes
fun getIndexesOfWordsStartingWithLetter(words: Array<String>, letter: Char): List<Int> {
    return words.mapIndexedNotNull { index, word ->
        if (word.startsWith(letter, ignoreCase = true)) index else null
    }
}

fun main() {
    val words = arrayOf("zero", "one", "two", "three", "four", "five", 
                        "six", "seven", "eight", "nine", "ten")
    val specificLetter = 't'
    
    val indexes = getIndexesOfWordsStartingWithLetter(words, specificLetter)
    
    println(indexes) 
}

  
     
/*
run:
  
[2, 3, 10]
 
*/

 



answered Mar 14, 2025 by avibootz
...