我想將一個char轉換爲一個int值。 我的方式toInt
的作品有點困惑。爲什麼使用toInt方法將'1'char轉換爲int結果爲49?
println(("123").toList) //List(1, 2, 3)
("123").toList.head // res0: Char = 1
("123").toList.head.toInt // res1: Int = 49 WTF??????
49沒有理由隨機彈出。 如何將char轉換爲int?
我想將一個char轉換爲一個int值。 我的方式toInt
的作品有點困惑。爲什麼使用toInt方法將'1'char轉換爲int結果爲49?
println(("123").toList) //List(1, 2, 3)
("123").toList.head // res0: Char = 1
("123").toList.head.toInt // res1: Int = 49 WTF??????
49沒有理由隨機彈出。 如何將char轉換爲int?
使用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/
.toInt
會給你ascii值。這可能是最簡單的寫
"123".head - '0'
如果你想處理非數字字符,你可以做
c match {
case c if '0' <= c && c <= '9' => Some(c - '0')
case _ => None
}
您還可以使用
"123".head.toString.toInt
對於簡單的數字爲int的轉換有是asDigit
:
scala> "123" map (_.asDigit)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
這工作。此外,我不得不使用'(someCharValue).toString'將char轉換爲字符串。我會在5分鐘內接受。 –
Integer.parseInt接受字符串yes。如果只需要第一個字符,請使用「1234」.substring(0,1)或「1234」.slice(0,1)。這會返回一個字符串。 請確保不要使用Kim Stebel建議的內容(c匹配{...})。這是非常糟糕的做法。 –