English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map

Java Set

Java entrée/sortie (I/O)

Java Reader/Writer

Autres sujets Java

Recherche du nombre d'occurrences des caractères (fréquence) dans une chaîne de caractères en Java

Java example complete set

Dans ce programme, vous apprendrez à rechercher le nombre d'occurrences des caractères (fréquence) dans une chaîne donnée.

Exemple : recherche du nombre d'occurrences de caractères, fréquence

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.

Java example complete set