English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to calculate the number of vowels and consonants in a sentence

Kotlin Example大全

In this program, you will learn to calculate the number of vowels, consonants, digits, and spaces in a given sentence in Kotlin.

Example1: Program to calculate vowels, consonants, digits, and spaces

fun main(args: Array<String>) {
    var line = "This website is aw"3som3."
    var vowels = 0
    var consonants = 0
    var digits = 0
    var spaces = 0
    line = line.toLowerCase()
    for (i in 0..line.length - 1)} {
        val ch = line[i]
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            ++vowels
        )} else if (ch in 'a'..'z') {
            ++consonants
        )} else if (ch in 'a'..9)} else if (ch in '0'..
            ++digits
        } else if (ch == ' ') {
            ++spaces
        }
    }
    println("Vowels: $vowels")
    println("Consonants: $consonants")
    println("Digits: $digits")
    println("Spaces: $spaces")
}

The output when running the program is:

Vowel: 6
Consonant: 11
Digit: 3
Space: 3

In the above example, each check has4condition.

  • The first if condition is to check if the character isVowel.

  • The else if condition after if is used to check if the character is a consonant. The order should be the same, otherwise, all the vowels are also considered as consonants.

  • The third condition (else if) is to check if the character is in0 to9between.

  • Finally, the last condition is to check if the character isSpaceCharacter.

For this, we use toLowerCase() to make the line lowercase. This is an optimization without checking uppercase A to Z and vowels.

We use the length() function to know the length of the string, and use for..in to get the character at the given index(position).

This is equivalent Java code:Java program to calculate the number of vowels and consonants in a sentence.

Example2: Program to count vowels, consonants, digits, and spaces

fun main(args: Array<String>) {
    var line = "This website is aw"3som3."
    var vowels = 0
    var consonants = 0
    var digits = 0
    var spaces = 0
    line = line.toLowerCase()
    for (i in 0..line.length - 1)} {
        val ch = line[i]
        when (ch) {
            'a', 'e', 'i', 'o', 'u' -> ++vowels
            in 'a'..'z' -> ++consonants
            in '0'..9' -> ++digits
            '' -> ++spaces
        }
    }
    println("Vowels: $vowels")
    println("Consonants: $consonants")
    println("Digits: $digits")
    println("Spaces: $spaces")
}

The output of the program is the same as the example1The same.

Here, you can see that we have used a simple when expression to replace if-The else statement makes the code shorter and easier to understand.

Kotlin Example大全