0

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

4 に答える 4

5

単純な数字から整数への変換には、次のものがありasDigitます。

scala> "123" map (_.asDigit)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
于 2012-09-28T20:24:52.763 に答える
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/を参照してください

于 2012-09-28T18:14:52.123 に答える
1

.toIntあなたにASCII値を与えます。おそらく書くのが最も簡単です

"123".head - '0'

数字以外の文字を処理したい場合は、次のことができます。

c match {
  case c if '0' <= c && c <= '9' => Some(c - '0')
  case _ => None
}
于 2012-09-28T18:15:30.437 に答える
0

使用することもできます

"123".head.toString.toInt
于 2012-09-28T20:01:39.793 に答える