如何计算字符串的字符? [英] How to count characters of a String?
问题描述
我是Scala的新手!我想计算一个字符串中出现char的次数。我该怎么做呢?我开始写这样的东西,但是我发现语法很难掌握。有帮助吗?
I am a pretty newbie to Scala! I would like to count the times a char occurs in a string. How do I do this? I started writing something like this but I find the syntax very hard to grasp. Any help?
var s = "hello"
var list = s.toList.distinct
list.foreach(println(s.count(_=='list')))
推荐答案
如果您想要将字符映射到计数,可以尝试执行以下操作:
You could try something like this if you wanted a Map of the chars to the counts:
val str = "hello"
val countsMap:Map[Char,Int] =
str.
groupBy(identity).
mapValues(_.size)
将扩展为更长的形式:
str.
groupBy(c => c).
mapValues(str => str.size)
因此, groupBy
我们是说我们要按字符串本身中的各个 Char
s分组。这样会产生一个 Map [Char,String]
,像这样:
So to break this down, in the groupBy
we are saying that we want to group by the individual Char
s in the String themselves. This will produce a Map[Char, String]
like so:
Map(e -> e, h -> h, l -> ll, o -> o)
然后,使用 mapValues
方法重新映射 Map
的值部分使用 String
的 .size
而不是 String
本身。
Then, you re-map the values portion of that Map
with the mapValues
method telling it to use the .size
of the String
and not the String
itself.
这篇关于如何计算字符串的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!