2

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
  • Try printing str[1]. What does that say? Commented Mar 4, 2020 at 3:20
  • try using substr() Commented Mar 4, 2020 at 3:31

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought str [n] returned a string. Now I know that str [n] returns a character. Thank you.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.