Kotlin String to Int value is wrong

Viewed 382

This is my code:

fun main(){
  val str = "123"
  println(str.toInt()) // 123
  println(str[1].toInt()) // 50 ???
}

I want number 2. But it's result number 50.

I didn't want ASCII code number.

How can I get a solution?

2 Answers

If you want to get the second character in the String, you can do

println(str[1])

And if you want to convert the second character to an Int, then you should do

println(str[1].toString().toInt())

Please note that toInt() can throw a NumberFormatException.

The ASCII value of character '2' is 50 (decimal). Looks like you want a substring operation to get the string "2" (or "23" ?) rather than character indexing that gets the char '2'.

Related