Home » Kotlin » Kotlin programs » Kotlin string programs

Kotlin program to find the frequency of character in a string

Kotlin | Frequency of a character in string: Here, we are going to learn how to check/find the frequency of a given character in a string in Kotlin programming language?
Submitted by IncludeHelp, on April 27, 2020

Given a string and a character, we have to find the frequency of the character in the string.

Example:

    Input:
    string = "IncludeHelp"
    character to find = 'e'

    Output:
    2

Program to find the frequency of character in a string in Kotlin

package com.includehelp.basic

import java.util.*

//Main Function, entry Point of Program
fun main(args: Array<String>) {
    // InputStream to get Input
    val scanner = Scanner(System.`in`)

    //Input String
    print("Enter String : ")
    val str = scanner.nextLine()

    //Input Character to check Frequency in Above input String
    print("Enter Character : ")
    val c = scanner.next()[0]

    var frequency=0
    //Count Frequency
    for (i in str.indices){
        if(c == str[i]){
            frequency++
        }
    }

    //Print Frequency of Character
    println("Frequency of $c is : $frequency")
}

Output

RUN 1:
Enter String : include help team
Enter Character : e
Frequency of e is : 3
---
Run 2:
Enter String : Kotlin is the Modern Programming Languagae
Enter Character : n
Frequency of n is : 4


Comments and Discussions!

Load comments ↻





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