Count all occurrences of a char within a string

i don't use Scala or even java but google search for "Scala string" brought me to here

which contains :

def
count (p: (Char) ⇒ Boolean): Int
Counts the number of elements in the string which satisfy a predicate.
p
the predicate used to test elements.
returns
the number of elements satisfying the predicate p.
Definition Classes
TraversableOnce → GenTraversableOnce

Seems pretty straight forward but i dont use Scala so don't know the syntax of calling a member function. May be more overhead than needed this way because it looks like it can search for a sequence of characters. read on a different result page a string can be changed into a sequence of characters and you can probably easily loop through them and increase a counter.


You can also take a higher level approach to look into substring occurrences within another string, by using sliding:

def countSubstring(str: String, sub: String): Int =
  str.sliding(sub.length).count(_ == sub)

"hello".count(_ == 'l') // returns 2

Tags:

Scala