How to get the index of the last instance of a character in a string with Kotlin

1 Answer

0 votes
fun main() {
    val s = "Kotlin is a cross-platform, general-purpose programming language"
    val characterToFind = 'o'

    val index = s.lastIndexOf(characterToFind)
    
    if (index != -1) {
        println("The last occurrence of '$characterToFind' is at index $index")
    } else {
        println("Character '$characterToFind' not found in the string")
    }
}



 
/*
run:

The last occurrence of 'o' is at index 46
 
*/

 



answered Dec 11, 2024 by avibootz
...