在Java中使用数组计算字母频率

我有一项作业,通过迭代字符串中的字符来执行字母频率分析。

我不确定如何使用数组来存储每个字母的频率。该数组必须按字母顺序排列,并且还存储非字母字符(包括空格)

不幸的是我必须使用一个数组来存储频率。

在 Java 中完成此任务的最佳方法是什么?


梵蒂冈之花
浏览 35回答 2
2回答

温温酱

使用流的高效方法Map<Character,&nbsp;Long>&nbsp;freq&nbsp;=&nbsp;Arrays.stream(arr). &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;collect(Collectors.groupingBy(Character::charValue,&nbsp;Collectors.counting()));

桃花长相依

一种直接的方法是使用2个数组,一个用于存储字符串中出现的字符,区分大小写,另一个用于存储其相应的频率。两个数组都使用字符串长度的大小进行声明,以下示例代码展示了如何仅使用数组和简单的逻辑来实现您想要的效果。示例代码String str = "The array must be in alphabetical order and also store non-alphabetical characters (including spaces)";char[] charArr = new char[str.length()];int[] freqArr = new int[str.length()];int idx = 0;for (int i = 0; i < str.length(); i++) {&nbsp; &nbsp; char c = str.charAt(i);&nbsp; &nbsp; boolean isFound = false;&nbsp; &nbsp; for (idx = 0; idx < str.length(); idx++) {&nbsp; &nbsp; &nbsp; &nbsp; if (freqArr[idx] == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (c == charArr[idx]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; freqArr[idx]++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isFound = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (!isFound) {&nbsp; &nbsp; &nbsp; &nbsp; charArr[idx] = c;&nbsp; &nbsp; &nbsp; &nbsp; freqArr[idx]++;&nbsp; &nbsp; }}//Sort charArr and freqArr arrayschar tempChar;int tempFreq;for (int i = 1; i < str.length(); i++) {&nbsp; &nbsp; for (int j = i; j > 0; j--) {&nbsp; &nbsp; &nbsp; &nbsp; if (charArr[j] < charArr [j - 1]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempChar = charArr[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; charArr[j] = charArr[j - 1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; charArr[j - 1] = tempChar;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempFreq = freqArr[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; freqArr[j] = freqArr[j - 1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; freqArr[j - 1] = tempFreq;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}打印字母频率for (int i = 0; i < str.length(); i++) {&nbsp; &nbsp; if (freqArr[i] != 0) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%s:%d", charArr[i], freqArr[i]);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}控制台输出[:13],[(:1],[):1],[-:1],[T:1],[a:13],[b:3],[c:6],[d: 3],[e:8],...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java