Split string doubt - ints.toString()[index]


#1

I have try to sum a number (29), by split it and sum the two numbers. But I have got some strange output. My code was:

When the input is 29 (n = 29)

    fun addTwoDigits(n: Int): Int {
        val n1 = n.toString()[0].toInt() // output: 50
        val n2 = n.toString()[1].toInt() // output: 57
        return n1+n2 // output: 107
    }

Wy it is not getting the right numbers?

I sloved it by making

fun addTwoDigits(n: Int): Int {
    val n1 = n.toString().substring(0,1).toInt() // output: 2
    val n2 = n.toString().substring(1,2).toInt() // output: 9
    return n1+n2 // output: 11
}

The n.toString().substring(1,2).toInt() gave me the right number. Please someone explain to me wy it is wrong?


#2

Your output is correct.
n.toString[0] is of type Char. Every char has character has an integer value ‘a’ is 97 and ‘z’ is 122 i think. And every other character in the alphabet is between those to. “Special” characters like {, /, etc have different values associated. It just happens to be that the character ‘2’ is 50. The numbers are not 0 to 9. I hope this makes sense.

Your second solution works, because substring does not return a character but a string.
Therefor "29".substring(0,1) correctly gets evaluated as "2"