java显示字符串中每个字母的出现情况?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
int count;
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
}
我试图在一个句子中显示每个字母(仅字母)的出现情况,但我迷路了。我已将字符串转换为字符数组,但现在我迷路了
例如,如果我输入一句话:“你好,你好吗?” 结果将是:
Occurrence of h: 1
Occurrence of e: 2
Occurrence of l: 2
Occurrence of o: 3
etc..
我知道我需要利用我的int计数,但我不知道如何做到这一点。我们的教授让我们使用这个:
c[26];
c[ch - 'a']++;
我不知道在这个小项目中应该在哪里使用这些
编辑:更新
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
sentence = sentence.toLowerCase();
int count[];
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
char alphabet[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
System.out.println();
}
}
# 1 楼答案
使用
HashMap<Character, Integer>
来跟踪。密钥是唯一的字符,整数计算您看到它的次数输出:
# 2 楼答案
我觉得没有理由在这里使用HashMap。HashMaps使用HashFunction将一些值映射到内存中的位置,以便更快地访问。在这种情况下,他将有相同的,或非常类似的东西,与数组和这个映射函数,是给他的(ch-'a')。此外,对于正在这样做的人来说,现在使用HashMap可能还为时过早
你的问题是你还不明白这个想法。 java中的字母有值(您可以检查ASCII表)。字母表中有26个字母,第一个是“a”,最后一个是“z”。所以你需要26个元素的数组。每次当字符串中有“a”时,你都想在数组中增加0处的元素,当你进入“b”时,你想增加1处的元素。。。。当你来到“z”元素25。所以,事实上,用(ch-'a')将字母映射到数组中,其中是字母出现的次数
你拿绳子吧。在上面放一个toLowerCase()的盒子,把它递过来数数字母,然后打印出你发现的内容