Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count char frequency in string with scala

Tags:

scala

I search a way to count the different chars from a string. The problem is that's not allowed to use any functions from the scala-api or to use vars (only val).

I want same result like that

val fruit: String = "dasisteintest"
println(fruit.groupBy(identity).mapValues(_.size))
Map(e -> 2, s -> 3, n -> 1, t -> 3, a -> 1, i -> 2, d -> 1)

In every try I made, I have at the end a list[(Char,Int)] where I have to change the Int. But because it's an immutable list I can't change it. How can I implement that counting char algorithm?

like image 692
theoretisch Avatar asked Feb 20 '26 08:02

theoretisch


1 Answers

You can use the following snippet:

val fruit: String = "dasisteintest"
val map = scala.collection.mutable.HashMap.empty[Char, Int]
for (symbol <- fruit) {
  if (map.contains(symbol))
    map(symbol) = map(symbol) + 1
  else
    map.+=((symbol, 1))
}
println(map)
like image 163
Aliaxander Avatar answered Feb 22 '26 01:02

Aliaxander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!