【发布时间】:2019-08-07 18:30:15
【问题描述】:
问题
我编写了这个程序来检查每个字母在用户输入的字符串中出现的次数。它工作得很好,但是有没有比为每个字符重复一个 26 元素长的数组更有效或替代的解决方案来完成这项任务?
代码
import java.util.Scanner;
public class Letters {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
System.out.println("Enter a string.");
String k = sc.nextLine();
String s = k.toUpperCase();
s = s.trim();
int l = s.length();
System.out.println("Checking string = " + s);
char ch;
for (int i = 0; i < l; i++) {
ch = s.charAt(i);
for (int j = 0; j < c.length; j++) {
if (ch == c[j]) {
f[j]++;
}
}
}
System.out.println("Char\tFreq");
for (int i = 0; i < c.length; i++) {
if (f[i] != 0) {
System.out.println(c[i] + "\t" + f[i]);
}
}
}
}
【问题讨论】:
-
我相信这个问题更适合-> codereview.stackexchange.com
-
一种简单的方法是使用 Stream API。见here。
-
你可以使用
f[ch - 'A']++来避免低效的迭代。 -
@Emma 感谢您的提示。我会这样做的。
标签: java arrays string performance char