Scala Program: Count vowels with if/else and pattern matching
Scala Control Flow Exercise-9 with Solution
Write a Scala program to count the number of vowels in a given string using if/else statements and pattern matching.
Sample Solution:
Scala Code:
object VowelCounter {
def main(args: Array[String]): Unit = {
// String in which you want to count vowels
val str: String = "Scala Programming"
// Count using if/else statements
val vowelCount: Int = countVowelsIfElse(str)
println(s"Number of vowels (if/else) in $str: $vowelCount")
// Count using pattern matching
val vowelCountMatch: Int = countVowelsMatch(str)
println(s"Number of vowels (pattern matching): $vowelCountMatch")
}
def countVowelsIfElse(str: String): Int = {
var count: Int = 0
for (ch <- str) {
if (isVowel(ch)) {
count += 1
}
}
count
}
def countVowelsMatch(str: String): Int = {
str.toLowerCase match {
case "" => 0
case s => s.count(isVowel)
}
}
def isVowel(ch: Char): Boolean = {
ch.toLower match {
case 'a' | 'e' | 'i' | 'o' | 'u' => true
case _ => false
}
}
}
Sample Output:
Number of vowels (if/else) in Scala Programming: 5 Number of vowels (pattern matching): 5
Explanation:
In the above exercise,
First, we define a variable str and assign it a value ("Hello, World!" in this case) representing the string in which we want to count vowels.
There are two functions: "countVowelsIfElse()" and "countVowelsMatch()". The first function uses if/else statements and a for loop to iterate over each character in the string. It checks if the character is a vowel using the isVowel function and increments the count if it is. After iterating through all the characters, it returns the vowels count.
The second function, "countVowelsMatch()", uses pattern matching and the count method to count the vowels in the string. It first converts the string to lowercase using the toLowerCase method to handle both uppercase and lowercase vowels. Then, it matches the string against an empty string ("") and returns 0 if the string is blank. If the string is not empty, it applies the count method on the string, passing the isVowel function as the argument, to count the vowels.
The isVowel function checks if a character is a vowel. It converts the character to lowercase using the toLower method. It matches it against the vowels 'a', 'e', 'i', 'o', and 'u'. If it matches any vowels, it returns true; otherwise, false.
Finally, we call both functions and print the results using println.
Scala Code Editor :
Previous: Check Palindrome using if/else and pattern matching.
Next: Find the largest element with pattern matching.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/control-flow/scala-control-flow-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics