Scala Program: Count vowels with if/else and pattern matching
Write a Scala program to count the number of vowels in a given string using if/else statements and pattern matching.
Pre-Knowledge (Before you start!)
- Basic Scala Syntax: Familiarity with writing and running Scala programs.
- String Manipulation: Knowledge of working with strings, including iterating through characters and converting case.
- If/Else Statements: Understanding how to use if/else statements for conditional logic.
- Pattern Matching: Awareness of using pattern matching for decision-making and filtering.
- Character Handling: Ability to check if a character is a vowel using conditions or pattern matching.
- Printing Output: Familiarity with the println() function to display output on the screen.
Hints (Try before looking at the solution!)
- Define the Main Object: Create an object with a main method, which serves as the entry point of the program.
- Initialize the String: Declare a variable to store the string in which you want to count vowels.
- Count Using If/Else: Write a function that iterates through each character of the string. Use an if/else statement to check if the character is a vowel and increment a counter if true.
- Count Using Pattern Matching: Write another function that uses pattern matching and the count method to count vowels. Convert the string to lowercase to handle case insensitivity.
- Create a Helper Function: Define a helper function to determine if a character is a vowel. Use pattern matching to check against 'a', 'e', 'i', 'o', 'u'.
- Display the Results: Use println() to print the number of vowels found using both methods.
- Test with Different Strings: Change the input string to verify the program works for various cases, including uppercase letters, special characters, and empty strings.
- Common Errors to Avoid:
- Forgetting to convert the string to lowercase, leading to incorrect results for uppercase vowels.
- Misplacing the logic for checking vowels, causing incorrect counts.
- Not handling edge cases like empty strings or strings without vowels, which may lead to unexpected behavior.
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics