How to count the letters, spaces, numbers and other characters of a string in Scala

1 Answer

0 votes
import scala.util.matching.Regex

def countCharacters(s: String): Unit = {
  val onlyLettersRegex: Regex = "^[a-zA-Z]$".r
  var letter = 0
  var spaces = 0
  var numbers = 0
  var otherchars = 0

  for (i <- s.indices) {
    s(i) match {
      case ch if onlyLettersRegex.findFirstIn(ch.toString).isDefined => letter += 1
      case ch if ch >= '0' && ch <= '9' => numbers += 1
      case ' ' => spaces += 1
      case _ => otherchars += 1
    }
  }

  println(s"letter: $letter")
  println(s"space: $spaces")
  println(s"number: $numbers")
  println(s"other: $otherchars")
}

val s = "Scala $100%     Prog()ramming   99 !!!"

countCharacters(s)



/*
run:
    
letter: 16
space: 10
number: 5
other: 7
    
*/

 



answered Aug 28, 2024 by avibootz
...