为什么使用toInt方法将'1'char转换为int会导致49?

时间:2012-09-28 18:13:04

标签: scala

我想将char转换为int值。 我对toInt的工作方式感到有些困惑。

println(("123").toList)         //List(1, 2, 3)
("123").toList.head             // res0: Char = 1
("123").toList.head.toInt       // res1: Int = 49 WTF??????

49无缘无故地随机弹出。 你如何以正确的方式将char转换为int?

4 个答案:

答案 0 :(得分:5)

对于简单的数字到int转换,有asDigit

scala> "123" map (_.asDigit)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)

答案 1 :(得分:2)

使用Integer.parseInt(“1”,10)。请注意,这里的10是基数。

val x = "1234"
val y = x.slice(0,1)
val z = Integer.parseInt(y)
val z2 = y.toInt //equivalent to the line above, see @Rogach answer
val z3 = Integer.parseInt(y, 8) //This would give you the representation in base 8 (radix of 8)

49不会随机弹出。它是“1”的ascii表示。见http://www.asciitable.com/

答案 2 :(得分:1)

.toInt将为您提供ascii值。写起来可能最容易

"123".head - '0'

如果要处理非数字字符,可以执行

c match {
  case c if '0' <= c && c <= '9' => Some(c - '0')
  case _ => None
}

答案 3 :(得分:0)

您也可以使用

"123".head.toString.toInt
相关问题