1. Introduction

In this tutorial, we’ll learn how to count all occurrences of a given char in a String in Scala.

For the purpose of the tutorial, we’re going to focus on the methods that are Scala-specific and available in the standard library.

2. Using count()

The most idiomatic way to perform the task is to use the count() method. The count() method accepts a function returning Boolean and automatically counts all elements for which the given function is true:

private def countWithCount(string: String, char: Char): Int = string.count(_ == char)

3. Using  filter()

We can also use filter() combined with size to achieve our goal:

private def countWithFilter(string: String, char: Char): Int = string.filter(_ == char).size

4. Using groupBy()

Another way we can count the occurrences of a char in a String is to compose three different methods *groupBy(), mapValues(), and reduce()*:

def countWithGroupBy(string: String, char: Char): Int =
    string.groupBy(identity).mapValues(_.map(_ => 1).reduce(_+_))(char)

The above pattern was used so often that, in Scala 2.13, a new method – mapGroupReduce() – was introduced to simplify its usage*.
*

5. Using Recursion

Although Scala offers some simple out-of-the-box solutions to solve our problem, it’s also possible to use tail-recursion for that:

 def countRecursive(string: String, char: Char): Int = {
    @tailrec
    def countRec(string: String, char: Char, count: Int): Int = {
      if(string.isEmpty) {
        count
      } else {
        val newCount = if(string.head == char) count + 1  else count
        countRec(string.tail, char, newCount)
      }
    }
    countRecursive(string, char)
  }

6. Summary

In this tutorial, we’ve learned different ways to count all occurrences of a char inside a String in Scala.

Because of the interoperability between Java and Scala, we can also use any of the methods described in our related article for Java.

As always, all the code samples are available over on GitHub.


» 下一篇: Scala 语言特点