msm082919
msm082919

Reputation: 707

Kotlin String to Int value is wrong

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?

Upvotes: 2

Views: 617

Answers (2)

mightyWOZ
mightyWOZ

Reputation: 8355

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.

Upvotes: 4

John3136
John3136

Reputation: 29266

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'.

Upvotes: 2

Related Questions