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)
Which would expand to the more longhand form:
str.
groupBy(c => c).
mapValues(str => str.size)
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With