2012-09-28 67 views

回答

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/

+0

這工作。此外,我不得不使用'(someCharValue).toString'將char轉換爲字符串。我會在5分鐘內接受。 –

+0

Integer.parseInt接受字符串yes。如果只需要第一個字符,請使用「1234」.substring(0,1)或「1234」.slice(0,1)。這會返回一個字符串。 請確保不要使用Kim Stebel建議的內容(c匹配{...})。這是非常糟糕的做法。 –

1

.toInt會給你ascii值。這可能是最簡單的寫

"123".head - '0' 

如果你想處理非數字字符,你可以做

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

但是,當然這會出現非數字字符。 – Chuck

+0

當然它... –

+0

我建議不要使用上面的代碼(c匹配{...})來處理這種情況。這是非常糟糕的做法。 –

0

您還可以使用

"123".head.toString.toInt 
5

對於簡單的數字爲int的轉換有是asDigit

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