w3resource

Scala Programming: Check whether a given character presents in a string between 2 to 4 times

Scala Programming Basic Exercise-23 with Solution

Write a Scala program to check whether a given character presents in a string between 2 to 4 times.

Sample Solution:

Scala Code:

object scala_basic {
  def test(str1: String): Boolean = {
      val count_char = str1.count{ n => n =='z' }
      count_char >= 2 && count_char <= 4
    }
     
   def main(args: Array[String]): Unit = {
      println("Result: " + test("frizz"));
      println("Result: " + test("zane"));
      println("Result: " + test("Zazz"));
      println("Result: " + test("false"));
    }
  }

Sample Output:

Result: true
Result: false
Result: true
Result: false

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to find the larger value from two positive integer values in the range 20..30 inclusive, or return 0 if neither is in that range.
Next: Write a Scala program to check whether two given positive integers have the same last digit.

What is the difficulty level of this exercise?