How to find all vowels in a string in Kotlin

Kotlin program to find all vowels in a string :

This tutorial will show you how you to find all vowels in a string. We can iterate through the characters of a string one by one and verify if it is a vowel or not one by one. Iterating through the characters of a string can be done in multiple ways. I will show you three different ways to solve this problem.

Method 1: Using forEach :

Using forEach, we can iterate through the characters of a string one by one and check each character inside this block. You can use one if block or one when block for that.

fun main() {
    var line = "Hello world"

    line.forEach{c ->
        when(c) {
            'a', 'e', 'i', 'o', 'u' -> println("$c is a vowel")
        }
    }
}

Or, we can use one if block like below:

fun main() {
    var line = "Hello world"

    line.forEach { c ->
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            println("$c is a vowel")
        }
    }
}

Method 2: Using indices:

fun main() {
    var line = "Hello world"

    for (i in line.indices) {
        when (line[i]) {
            'a', 'e', 'i', 'o', 'u' -> println("${line[i]} is a vowel")
        }
    }
}

The same problem we can solve using an if block.

Method 3: Converting it to an array:

We can also convert the string to an array and check for each character:

fun main() {
    var line = "Hello world"

    for (c in line.toCharArray()) {
        when (c) {
            'a', 'e', 'i', 'o', 'u' -> println("$c is a vowel")
        }
    }
}

Here, toCharArray is used to convert the string to an array.

Kotlin find vowel string