English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à rechercher le nombre d'occurrences des caractères (fréquence) dans une chaîne donnée.
public class Frequency { public static void main(String[] args) { String str = "This website is awesome."; char ch = 'e'; int frequency = 0; for(int i = 0; i < str.length(); i++}) { if(ch == str.charAt(i)) { ++frequency; } } System.out.println("Frequency of ", + ch + " = " + frequency); } }
When running this program, the output is:
Frequency of e = 4
In the above program, use the string method length() to find the length of the given string str.
We use the charAt() function to loop through each character in the string, which 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.
In the end, we get a total count of characters stored and print the frequency value.