Anonymous Kotlin function: Count vowels in a string
Kotlin Lambda: Exercise-11 with Solution
Write an anonymous Kotlin function to count the number of vowels in a 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.
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/kotlin-exercises/lambda/kotlin-lambda-exercise-11.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics