java - 计算字符串中的字符频率(Java)

标签 java

既然我被分配做一个查找字符串中字符出现频率的问题 这是来自 geeksforgeeks 的示例,但我无法理解它在做什么?所以我需要有人帮我解释一下。

Input : geeksforgeeks
Output :
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1

这是代码


class NoOfOccurenceOfCharacters { 
    static final int MAX_CHAR = 256; 
  
    static void getOccuringChar(String str) 
    { 
        // Create an array of size 256 i.e. ASCII_SIZE 
        int count[] = new int[MAX_CHAR]; 
  
        int len = str.length(); 
  
        // Initialize count array index 
        for (int i = 0; i < len; i++) 
            count[str.charAt(i)]++; 
  
        // Create an array of given String size 
        char ch[] = new char[str.length()]; 
        for (int i = 0; i < len; i++) { 
            ch[i] = str.charAt(i); 
            int find = 0; 
            for (int j = 0; j <= i; j++) { 
  
                // If any matches found 
                if (str.charAt(i) == ch[j])  
                    find++;                 
            } 
  
            if (find == 1)  
                System.out.println("Number of Occurrence of " + 
                 str.charAt(i) + " is:" + count[str.charAt(i)]);             
        } 
    } 
    public static void main(String[] args) 
    { 
        Scanner sc = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        getOccuringChar(str); 
    } 
} 

输出

Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1

count[str.charAt(i)]++ 实际上是做什么的? 我对这部分感到困惑,请有人解释一下吗?

为什么会有find = 0

最佳答案

嗯,count 是一个具有 256 个槽的 int[]:

int count[] = new int[MAX_CHAR]; // MAX_CHAR is 256

您的算法定义 MAX_CHAR = 256,因为它假设字符串仅包含 8 位 ASCII 字符。

[0, 0, ..., 0, 0] // 256 slots

现在,您正在迭代字符串 str 中的每个字符并将其转换为整数(请参阅 type casting of primitives in Java )。 A 将转换为 65 ( ASCII table ),B 将转换为 66,依此类推。转换的 int 是要递增的槽。因此,字符串 A 会导致索引 65 处的整数增加。您的问题主要是关于

count[str.charAt(i)]++

这意味着:

char c = str.charAt(i);    // c = A
int index = c;             // c = A, casted to an int = 65
count[index]++             // increments the int at position 65

结果:

[0, 0, ..., 1, ..., 0, 0]
            ^ index 65

下一个 A 将再次增加索引 65 处的 int:

[0, 0, ..., 2, ..., 0, 0]
            ^ index 65

关于java - 计算字符串中的字符频率(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59466548/

相关文章:

java - 在 Spark、Java 中合并元组两个值的数据

java - TestNG 类路径设置发生 JNI 错误

java - 如果必须填充数组,我该如何使它们相等?

java - 如何选择其中没有其他 div 的 div 元素?

java - 使用内容正文中包含越南字符的多部分进行放心的 POST 调用

java - Firebase 离线 setValue 上没有 CompletionListener

java - 处理非递减的颜色亮度序列

java - 使用 Java 或其他方式发送 GET 和 POST 请求而没有响应

java - JProgressBar 显示奇怪的橙色波浪

java - 如何减少自定义解串器中 if 的数量