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

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

问题描述

我只想总结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

$ b b

所以我尝试了

So I tried

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值为String字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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