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

1 Answer

0 votes
fun getFirstRepeatedCharacter(s: String): Char {
    val len = s.length

    for (i in 0 until len) {
        for (j in 0 until i) {
            if (s[i] == s[j]) {
                return s[i]
            }
        }
    }

    return ' '
}

fun main() {
    val s = "abcdxypcbop"
    val result = getFirstRepeatedCharacter(s)

    if (result != '-') {
        println("First repeated character: $result")
    } else {
        println("No repeated characters")
    }
}
 
 
 
  
/*
run:
    
First repeated character: c
    
*/

 



answered Dec 2, 2024 by avibootz
...