Scala char 到 int 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16241923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:14:01  来源:igfitidea点击:

Scala char to int conversion

scala

提问by flavian

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;
};

This is a function that takes a String like 12345and 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 Charto Intactually returning?

这是一个接受类似 String 的函数,12345并且应该返回1 * 2 * 3 * 4 * 5. 然而,我回来没有任何意义。从CharInt实际返回的隐式转换是什么?

It appears to be adding 48to all the values. If instead I do product = product * (x.toInt - 48)the results are correct.

它似乎增加48了所有的价值。相反,如果我这样做product = product * (x.toInt - 48),结果是正确的。

回答by om-nom-nom

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':

这是有道理的:这就是在 ASCII 表中编码字符的方式:0 字符映射到十进制 48,1 映射到 49 等等。所以基本上当你将 char 转换为 int 时,你需要做的就是减去“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

Or just use x.asDigit, as @Reimer said

或者只是使用x.asDigit,正如@Reimer 所说

scala> '1'.asDigit
// res5: Int = 1