Home » Kotlin » Kotlin programs » Kotlin string programs

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

Here, we are going to learn how to find total number of vowels, consonants, digits and spaces in a string in Kotlin programming language?
Submitted by IncludeHelp, on April 29, 2020

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

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



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.