Java:计算字符串中字母的出现次数
我正在尝试编写一个程序,计算字符串中字母的出现次数。例如,如果用户输入Java,它将显示j:1A:2V:1。然而,我的程序似乎有问题,当我输入java这个词时,它显示的是j:0a:1v:0Java:计算字符串中字母的出现次数,java,Java,我正在尝试编写一个程序,计算字符串中字母的出现次数。例如,如果用户输入Java,它将显示j:1A:2V:1。然而,我的程序似乎有问题,当我输入java这个词时,它显示的是j:0a:1v:0 Scanner myScanner = new Scanner(System.in); String s = myScanner.nextLine(); int i = 0; int j = 0; int cnt = 0; int length = s.leng
Scanner myScanner = new Scanner(System.in);
String s = myScanner.nextLine();
int i = 0;
int j = 0;
int cnt = 0;
int length = s.length();
char ch;
for (i = 0; i < length; i++) {
ch = s.charAt(i);
if (s.indexOf(ch) < i)
continue;
for (j = (i + 1); j < length; j++) {
if (s.charAt(j) == ch)
cnt++;
}
System.out.println(ch + ": " + cnt);
cnt = 0;
}
你的第二个for循环不是为每个字母搜索整个单词 例如,当搜索j时,它只查看ava,因为它从i+1开始,即
(0 + 1) = 1
在字符串java中,这是一个索引,索引为0。改变
到
您想要的输出:
Enter your String: Mascarena
M: 1
a: 3
s: 1
c: 1
r: 1
e: 1
n: 1
代码中的错误:
for (j = (i + 1); j < length; j++) { //It is omitting the first letter and searches the remaining
if (s.charAt(j) == ch)
cnt++;
}
已纠正:
for (j = 0; j < length; j++) { //For a specific letter searches the whole string.
if (s.charAt(j) == ch)
cnt++;
}
输入:aabacbd
输出:a3b2c1d1Caps被认为是在网络上叫喊。请使用普通大小写。首先编写一个纯函数,计算字符串中字母的出现次数。方法签名看起来类似于静态Map countLettersString s。
for (j = (i + 1); j < length; j++) { //It is omitting the first letter and searches the remaining
if (s.charAt(j) == ch)
cnt++;
}
for (j = 0; j < length; j++) { //For a specific letter searches the whole string.
if (s.charAt(j) == ch)
cnt++;
}
public static String numberOfOccurence(String data) {
String result = "";
while (!data.isEmpty()) {
result += String.valueOf(data.charAt(0))+ StringUtils.countOccurrencesOf(data, String.valueOf(data.charAt(0)));
data = data.replaceAll(String.valueOf(data.charAt(0)), "");
}
return result;
}