gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:21:41 25 4
gpt4 key购买 nike

既然我被分配做一个查找字符串中字符出现频率的问题这是来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com