Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count characters of a String?

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')))
like image 433
lioli Avatar asked Nov 29 '22 23:11

lioli


1 Answers

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 Chars 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.

like image 154
cmbaxter Avatar answered Dec 05 '22 11:12

cmbaxter