Anonymous Kotlin function: Count vowels in a string
Write an anonymous Kotlin function to count the number of vowels in a string.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should be familiar with the following concepts:
- Strings: A string is a sequence of characters. In this problem, we need to analyze each character of a string.
- Anonymous Functions: An anonymous function is a function that does not have a name. It can be assigned to a variable and used like a regular function.
- Lists: Lists in Kotlin are used to store collections of items. Here, we use a list to store vowels for comparison.
- Loops: Understanding how to iterate over a string using a for loop is essential to process each character.
- Character Comparison: We need to compare each character of the string with vowels and count the occurrences.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Define an anonymous function that takes a string as a parameter and returns an integer.
- Hint 2: Create a list of vowel characters (a, e, i, o, u) for comparison.
- Hint 3: Convert the input string to lowercase so that both uppercase and lowercase vowels are treated the same.
- Hint 4: Use a loop to iterate over the string and check if each character is in the vowels list. If yes, increase the count.
- Hint 5: Return the total count of vowels found in the string.
Sample Solution:
Kotlin Code:
fun main() {
val countVowels: (String) -> Int = fun(str: String): Int {
val vowels = listOf('a', 'e', 'i', 'o', 'u')
var count = 0
for (char in str.lowercase()) {
if (char in vowels) {
count++
}
}
return count
}
val str = "Hello, World!"
val vowelCount = countVowels(str)
println("Original string: $str")
println("Number of vowels in '$str' is: $vowelCount")
}
Sample Output:
Original string: Hello, World! Number of vowels in 'Hello, World!' is: 3
Explanation:
In the above exercise -
- We define an anonymous function called countVowels with the type (String) -> Int. It takes a string as its parameter and returns the count of vowels in the string as an integer.
- Inside the countVowels function, we create a list called vowels that contains all vowel characters. We also initialize a variable count to keep track of the vowel count, initially set to 0.
- We iterate through each character in the input string str using a for loop. We convert each character to lowercase using the toLowerCase() function to handle both uppercase and lowercase vowels. If the character is found in the vowels list, we increment the count variable.
- After the loop, we return the final value of count, which represents the number of vowels in the string.
Kotlin Editor:
Previous: Find maximum element in array.
Next: Sum of odd numbers in a list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics