Count all occurrences of a char within a string
ScalaScala Problem Overview
Does Scala have a native way to count all occurrences of a character in a string?
If so, how do I do it?
If not, do I need to use Java? If so, how do I do that?
Thanks!
Scala Solutions
Solution 1 - Scala
"hello".count(_ == 'l') // returns 2
Solution 2 - Scala
i don't use Scala or even java but google search for "Scala string" brought me to [here][1]
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. [1]: http://www.scala-lang.org/api/current/scala/collection/immutable/StringOps.html
Solution 3 - Scala
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)