English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to find the frequency (occurrence) of a character in a given string in Kotlin.
fun main(args: Array<String>) { val str = "This website is awesome." val ch = 'e' var frequency = 0 for (i in 0..str.length - 1) { if (ch == str[i]) { ++frequency } } println("The frequency of $ch = $frequency") }
When running the program, the output is:
Frequency of 'e' = 4
In the above program, we use the string method length() to find the length of the given string str.
We use a loop to iterate through each character in the string str, the function accepts an index (i) and returns the character at the given index.
We compare each character with the given character ch. If it matches, we increase the frequency value1.
Finally, we get a total count of occurrences of the character stored in it, and print the value of frequency.
The equivalent Java code is as follows:Java Program to Find Frequency of Characters in a String.