Scala - How to count the number of occurrences of a character in a String

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.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.