Scala char 到 int 的转换 [英] Scala char to int conversion
问题描述
def multiplyStringNumericChars(list: String): Int = {
var product = 1;
println(s"The actual thing + $list")
list.foreach(x => { println(x.toInt);
product = product * x.toInt;
});
product;
};
这是一个函数,它接受一个类似于 12345
的字符串,并且应该返回 1 * 2 * 3 * 4 * 5
的结果.然而,我回来没有任何意义.从 Char
到 Int
的隐式转换实际上返回了什么?
This is a function that takes a String like 12345
and should return the result of 1 * 2 * 3 * 4 * 5
. However, I'm getting back doesn't make any sense. What is the implicit conversion from Char
to Int
actually returning?
它似乎将 48
添加到所有值.如果我改为 product = product * (x.toInt - 48)
结果是正确的.
It appears to be adding 48
to all the values. If instead I do product = product * (x.toInt - 48)
the results are correct.
推荐答案
它确实有道理:这就是字符编码的方式ASCII 表:0 字符映射到十进制 48,1 映射到 49,依此类推.所以基本上当你将char转换为int时,你需要做的就是减去'0':
It does make sense: that is the way how characters encoded in ASCII table: 0 char maps to decimal 48, 1 maps to 49 and so on. So basically when you convert char to int, all you need to do is to just subtract '0':
scala> '1'.toInt
// res1: Int = 49
scala> '0'.toInt
// res2: Int = 48
scala> '1'.toInt - 48
// res3: Int = 1
scala> '1' - '0'
// res4: Int = 1
或者只是使用 x.asDigit
,正如@Reimer 所说
Or just use x.asDigit
, as @Reimer said
scala> '1'.asDigit
// res5: Int = 1
这篇关于Scala char 到 int 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!