gpt4 book ai didi

java - 需要帮助根据用户输入列出字符的频率

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:56 26 4
gpt4 key购买 nike

我当前的代码列出了字母数组的频率,我想知道是否有一种方法可以合并数字和用户可用的所有标点符号。 (即 ASCII 文本)我很感激任何帮助!

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 0;
String str;
char c, ch;


System.out.print("Enter a String : ");
str=scan.nextLine();

i=str.length();
for(c='A'; c<='z'; c++)
{
k=0;
for(j=0; j<i; j++)
{
ch = str.charAt(j);
if(ch == c)
{
k++;
}
}
if(k>0)
{
System.out.println( c + " " + k );
}



}
}
}

input
Enter a String : jhdvaevaecvieabvuae[;;;/'[298734327
output
[ 2
a 4
b 1
c 1
d 1
e 4
h 1
i 1
j 1
u 1
v 4

此外,此代码已准备好区分大小写。

最佳答案

您可以使用以下步骤。创建一个容量为 128(ascii 字符集大小)的频率数组。将频率的所有元素初始化为 0。现在扫描输入字符串的每个字符,并将频率数组中的频率加 1。数组的索引可以通过将当前字符转换为其整数表示来计算。为了供您引用,您可以查看下面提供的代码。

public String computeFrequency(String input) {
int []frequecy = new int[128]; // each element of array represent frequency of some character indexed by character's ascii code
for(char ch: input.toCharArray()) {
int intCurrentChar = (int) ch; // get ascii code of current character. It can be obtained by casting character to integer in java.
frequecy[intCurrentChar]++; // increase the frequency of current character
}

// collect all non zero frequency to string
StringBuilder sbr = new StringBuilder();
for(int frequencyIndex = 0; frequencyIndex <128; frequencyIndex++) {
if( frequecy[frequencyIndex]>0) {
char ch = (char) frequencyIndex; // get ascii character from ascii code. It can be obtained by casting integer to character in java.
sbr.append(ch).append(" ").append(System.lineSeparator());
}
}

return sbr.toString();
}

关于java - 需要帮助根据用户输入列出字符的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51184062/

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