原文: https://beginnersbook.com/2019/04/java-program-to-find-the-occurrence-of-a-character-in-a-string/
在本教程中,我们将编写一个 Java 程序来查找String中字符的出现。
编程以查找字符串中字符的出现
在这个程序中,我们发现String中每个字符的出现。为此,我们首先创建一个大小为 256(ASCII 上限)的数组,这里的想法是将出现次数存储在该字符的 ASCII 值中。例如,'A'的出现将存储在计数器[65]中,因为A的 ASCII 值是 65,类似地,其他字符的出现存储在它们的 ASCII 索引值中。
然后我们创建另一个数组array来保存给定String的字符,然后我们将它们与String中的字符进行比较,当找到匹配时,使用counter数组显示该特定字符的计数。
class JavaExample {static void countEachChar(String str){//ASCII values ranges upto 256int counter[] = new int[256];//String lengthint len = str.length();/* This array holds the occurrence of each char, For example* ASCII value of A is 65 so if A is found twice then* counter[65] would have the value 2, here 65 is the ASCII value* of A*/for (int i = 0; i < len; i++)counter[str.charAt(i)]++;// We are creating another array with the size of Stringchar array[] = new char[str.length()];for (int i = 0; i < len; i++) {array[i] = str.charAt(i);int flag = 0;for (int j = 0; j <= i; j++) {/* If a char is found in String then set the flag* so that we can print the occurrence*/if (str.charAt(i) == array[j])flag++;}if (flag == 1)System.out.println("Occurrence of char " + str.charAt(i)+ " in the String is:" + counter[str.charAt(i)]);}}public static void main(String[] args){String str = "beginnersbook";countEachChar(str);}}
输出:

