Search code examples
kotlinstringindexoutofbounds

Kotlin: Run length encoding


The program works, however, I still get a logical error: the final letter doesn't run through. For example, when I enter aaaabbbbccccdddd the output I get is a4b4c4 but there is no d4.

fun main () {

    val strUser = readLine()!!.toLowerCase()
    val iLength = strUser!!.length
    var iMatch : Int = 0
    var chrMatch : Char = strUser[0]

    for (i in 0..iLength) {

        if (strUser[i] == chrMatch) {

            iMatch += 1
        }else {
            print("$chrMatch$iMatch")
            chrMatch = strUser[i]
            iMatch = 1

        }


    }


}

Solution

  • strUser contains chars by indexes from 0 to iLength - 1 so you have to write for (i in 0 until iLength) instead of for (i in 0..iLength)

    But Tenfour04 is completely right, you can just iterate strUser without indexes:

    fun main() {
        val strUser = readLine()!!.toLowerCase()
        var iMatch: Int = 0
        var chrMatch: Char = strUser[0]
    
        for (char in strUser) {
            if (char == chrMatch) {
                iMatch += 1
            } else {
                print("$chrMatch$iMatch")
                chrMatch = char
                iMatch = 1
            }
        }
    }