How to find the first non-repeated character in a string with Kotlin

1 Answer

0 votes
fun getFirstNonRepeatedCharacter(str: String): Char? {
    for (ch in str) {
        if (str.indexOf(ch) == str.lastIndexOf(ch)) {
            return ch
        }
    }
    return null
}

fun main() {
    val s = "kotlin programming"
    
    val ch = getFirstNonRepeatedCharacter(s)
    
    print(ch)
}


 
/*
run:

k
 
*/

 



answered Jan 4, 2025 by avibootz
...