解决方法:字符串中字母的出现次数



我正在尝试计算字符串中字母的出现次数。从技术上讲,我编写的代码可以做我想要的,但不是我想要的方式。例如,如果我输入"Hello World",我希望我的代码返回"a=0 b=0 c=0 d=0 e=1 等..."使用我编写的代码,它返回"H=1、e=1、l=2 等...">

另外,我将如何确保它不区分大小写并且不计算空格。

法典:

import java.util.Scanner;
public class Sequence {
private static Scanner scan = null;
public static void main(String[] args) {
scan = new Scanner(System.in);
String str = null;
System.out.print("Type text: ");
str = scan.nextLine();
int[] count = new int[255];
int length = str.length();
for (int i = 0; i < length; i++) 
{
count[str.charAt(i)]++;
}
char[] ch = new char[str.length()];
for (int i = 0; i < length; i++) 
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) 
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1) 
{
System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");
}
}
}
}

正如我在原始评论中暗示的那样,您只需要一个包含 26 个int的数组,因为字母表中只有 26 个字母。在我分享代码之前,重要的是要注意 Javachar是一个整数类型(例如,'a' + 1 == 'b'(。该属性很重要,因为它允许您确定数组中的正确偏移量(尤其是在强制输入为小写的情况下(。像这样,

Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
}
System.out.println();

如果您真的想查看所有计数为零的字母(对我来说似乎毫无意义(,请更改

if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}

删除if,然后

System.out.printf("%c=%d ", 'a' + i, count[i]);

str = scan.nextLine();更改为str = scan.nextLine().toLowerCase().replaceAll("\s+","");

.toLowerCase()是一种使字符串中的每个字符都小写的方法。

.replaceAll()是一种用一个字符替换另一个字符的方法。在这种情况下,它将不带空格替换空格。