Kotlin function: Count vowels in a string
Kotlin Function: Exercise-3 with Solution
Write a Kotlin function `countVowels` that counts the number of vowels in a given string.
Sample Solution:
Kotlin Code:
fun countVowels(input: String): Int {
val vowels = listOf('a', 'e', 'i', 'o', 'u')
var count = 0
for (char in input.lowercase()) {
if (char in vowels) {
count++
}
}
return count
}
fun main() {
val str = "Kotlin, function!"
val vowelCount = countVowels(str)
println("The number of vowels in '$str' is $vowelCount")
}
Sample Output:
The number of vowels in 'Kotlin, function!' is 5
Explanation:
In the above exercise -
- The "countVowels()" function takes a String parameter named input, representing the string in which the vowels need to be counted.
- A list of vowels is created, containing lowercase vowels ('a', 'e', 'i', 'o', 'u').
- A variable count is initialized to 0 to keep track of the vowel count.
- A for loop is used to iterate over each character in the input string (input. lowercase() is used to convert the string to lowercase for case-insensitive comparison).
- Inside the loop, each character is checked if it exists in the vowel list. If it does, the count is incremented.
- Finally, the count value is returned as the result of the function.
- In the "main()" function, a sample string str is defined.
- The "countVowels()" function is called with the string as an argument, and the result is stored in the "vowelCount" variable.
- The number of vowels in the string is then printed to the console using string interpolation.
Kotlin Editor:
Previous: Print even numbers from an array.
Next: Kotlin function: Reverse a string.
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/function/kotlin-function-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics