By Alvin Alexander. Last updated: April 19, 2018
Scala String FAQ: How can I count the number of times (occurrences) a character appears in a String?
Use the count
method on the string, using a simple anonymous function, as shown in this example in the REPL:
scala> "hello world".count(_ == 'o') res0: Int = 2
There are other ways to count the occurrences of a character in a string, but that's very simple and easy to read.