字符或字符串 ->Scala 中的 Unicode 值? [英] Char or String -> Unicode value in Scala?
问题描述
所以我正在完成不耐烦的 Scala"中的一些练习,其中之一是:
So I'm working through a few of the exercises in "Scala for the Impatient" and one of them is:
编写一个 for
循环来计算字符串中所有字母的 Unicode 代码的乘积.例如,你好"中的字符的乘积为 9415087488 L.
Write a for
loop for computing the product of the Unicode codes of all letters in a string. For example, the product of the characters in "Hello" is 9415087488 L.
下一个问题是做同样的事情,但没有 for
循环 - 它暗示我们应该检查 Scaladoc 中的 StringOps
.
The next problem is to do the same, but without a for
loop - it hints that we should check StringOps
in Scaladoc.
我检查了 Scaladoc 中的 RichChar
和 StringOps
部分,也许我读错了或找错了地方,但我找不到任何让我心动的东西以匹配他们的输出.到目前为止,我已经尝试过:
I checked the RichChar
and StringOps
section in Scaladoc, and perhaps I'm misreading or looking in the wrong places, but I can't find anything that gets me to match their output. I've thus far tried:
scala> x.foldLeft(1)(_ * _.toInt)
res0: Int = 825152896
scala> x.foldLeft(1)(_ * _.getNumericValue)
res5: Int = 2518992
scala> x.foldLeft(1)(_ * _.intValue())
res6: Int = 825152896
scala> var x = 1
x: Int = 1
scala> for (c <- "Hello") x *= c.toInt
scala> x
res12: Int = 825152896
与他们的输出不匹配.
如何以 for
和非 for
方式执行此操作?
How do I do this, in both the for
and non-for
way?
谢谢!
推荐答案
当你做 x.foldLeft(1)(_ * _.toInt)
时,结果类型将推断为 x.foldLeft(1)(_ * _.toInt)
code>Int,但 9415087488 太大,Int
无法存储它.
When you do x.foldLeft(1)(_ * _.toInt)
, the result type will be inference to an Int
, but 9415087488 is too large for an Int
to store it.
所以你需要告诉 Scala 使用 Long
来存储它.
So you need to tell Scala using Long
to store it.
scala> val x = "Hello"
x: java.lang.String = Hello
scala> x.foldLeft(1L)(_ * _.toInt)
res1: Long = 9415087488
scala> var x: Long = 1
x: Long = 1
scala> for (c <- "Hello") x *= c.toInt
scala> x
res7: Long = 9415087488
这篇关于字符或字符串 ->Scala 中的 Unicode 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!