string - String 字符的 Scala int 值

标签 string scala char int

我只想对 BigInt 的数字求和。我能做到

scala> "1 2 3".split(" ").map(_.toInt).sum
res23: Int = 6

所以我尝试了

scala> BigInt(123).toString().map(_.toInt).sum
res24: Int = 150

这不起作用,因为它将字符映射到它们的 Unicode 值。

下面的方法都可以,但是有没有比使用 Java 静态方法或额外的 toString 转换更优雅的方法?

BigInt(123).toString().map(Character.getNumericValue(_)).sum
BigInt(123).toString().map(_.toString.toInt).sum

(我还使用递归函数来完成此操作,完全避开字符串,但我对简洁的 1-liner 感兴趣。)

最佳答案

哇...这些答案到处都是!在这里,执行以下操作:

BigInt(123).toString().map(_.asDigit).sum

关于string - String 字符的 Scala int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6238353/

相关文章:

列表中字符串的python模式切割

Scala特征和结构类型: can a trait extend a structural type and then call super?

c - 'jpg_name' 可以在此函数中使用未初始化的 [-Werror=uninitialized]

c++ - C++错误: expected ',' or ';' before '{' token when their is

java - 如何在不暂停程序的情况下获取字符

c - 读取系统调用不检测文件结束

c++ - 为什么这个字符串到整数的转换函数要减1?

scala - 为什么 spark 应用程序失败并显示 java.lang.NoClassDefFoundError : com/sun/jersey/api/client/config/ClientConfig even though the jar exists?

scala - Scala 中的列表未更新

java - Android Java - 字符串中的字符串变量?