w3resource

Kotlin function: Count vowels in a string


Write a Kotlin function `countVowels` that counts the number of vowels in a given string.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • String Manipulation.
  • Lists in Kotlin.
  • Loops in Kotlin.
  • Conditional Statements.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Create a Vowel List.
  • Convert to Lowercase.
  • Iterate Through Characters.
  • Check for Vowels.
  • Return the Count.
  • Test with Different Strings.
  • Common Errors to Avoid:
    • Forgetting to convert to lowercase.
    • Misplacing if logic.
    • Not initializing the counter correctly.

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.

Go to:


PREV : Print even numbers from an array.
NEXT : Kotlin function: Reverse a string.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.