Q:

Kotlin program to find total number of vowels, consonants, digits and spaces in a string

belongs to collection: Kotlin String Programs

0

Given a string, we have to count the total number of vowels, consonants, digits and spaces in a string.

Example:

    Input:
    string = "Heloo IncludeHelp this is your code 123#$567"

    Output:
    Vowels : 13
    Consonants : 17
    Digits : 6
    white Spaces : 6

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find total number of vowels, consonants, digits and spaces in a string in Kotlin

package com.includehelp.basic

import java.util.*

//Main function, Entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val sc = Scanner(System.`in`)

    var vowels=0
    var consonants=0
    var whitespace=0
    var digits=0
    
    
    //Input String Value
    println("Enter String : ")
    val sentence = sc.nextLine()

    //check for Null or Empty String
    if(!sentence.isNullOrEmpty()){
        //Convert String to lower case
        val s=sentence.toLowerCase()

        //iterate loop to count vowels, consonants, digits and spaces
        for(i in s.indices){
           when(s[i]){
               'a','e' ,'i' ,'o' ,'u' -> vowels++
               in 'a'..'z' -> consonants++
               in '0'..'9' -> digits++
               ' ' -> whitespace++
           }
        }

        println("Vowels : $vowels")
        println("Consonants : $consonants")
        println("Digits : $digits")
        println("white Spaces : $whitespace")
    }
    else{
        println("Sentence is Null or Empty")
    }
}

Output

Run 1:
Heloo IncludeHelp this is your code 123#$567
Vowels : 13
Consonants : 17
Digits : 6
white Spaces : 6
---
Run 2:
Delhi Corona Virus Death Count is 567
Vowels : 12
Consonants : 16
Digits : 3
white Spaces : 6

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program to check for Empty, Blank or NULL s... >>
<< Kotlin program to check whether a character is vow...