字符串字符的Scala int值 [英] Scala int value of String characters

查看:25
本文介绍了字符串字符的Scala int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想对 BigInt 的数字求和.我可以的

I just want to sum the digits of a BigInt. I can do

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

所以我尝试了

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

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

This doesn't work because it maps the characters to their Unicode values.

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

Both the following work, but is there a more elegant way than using the Java static method or an extra toString conversion?

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

(我也使用递归函数完成了它,完全避开了字符串,但我对简洁的 1-liner 感兴趣.)

(I've also done it using a recursive function, sidestepping strings altogether, but I'm interested here in a concise 1-liner.)

推荐答案

哇...这些答案到处都是!在这里,这样做:

Wow... these answers are all over the place! Here, do this:

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

这篇关于字符串字符的Scala int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆