目录
1、创建两个数组(储存A-z的字符及出现次数)
char[] list = new char[52];
for (int i = 0; i < list.length; i++) {
if (i < 26)
list[i] = (char) ('A' + i);
else
list[i] = (char) (list[i - 26] + 32);
}
int[] list2 = new int[52];
2、二分法遍历并计数
if (('A' <= s1.charAt(i) && s1.charAt(i) <= 'Z') ||
('a' <= s1.charAt(i) && s1.charAt(i) <= 'z'))
{
int k = Arrays.binarySearch(list, s1.charAt(i));
list2[k] = list2[k] + 1;
}
3、示例
public class CharacterTimes {
public static void main(String[] args) throws Exception {
char[] list = new char[52];
for (int i = 0; i < list.length; i++) {
if (i < 26)
list[i] = (char) ('A' + i);
else
list[i] = (char) (list[i - 26] + 32);
}
int[] list2 = new int[52];
File file = new File("Text.txt"); // 先建立文件
Scanner input = new Scanner(file);
while (input.hasNext()) {
String s1 = input.nextLine();
for (int i = 0; i < s1.length(); i++)
if (('A' <= s1.charAt(i) && s1.charAt(i) <= 'Z') ||
('a' <= s1.charAt(i) && s1.charAt(i) <= 'z'))
{
int k = Arrays.binarySearch(list, s1.charAt(i));
list2[k] = list2[k] + 1;
}
}
input.close();
for (int i = 0; i < 52; i++) {
System.out.print("Number of " + list[i] + "'s:" + list2[i]+" ");
if (i % 9 == 8)
System.out.println();
}
}
}
Number of A's:0 Number of B's:1 Number of C's:0 Number of D's:1 Number of E's:0 Number of F's:0 Number of G's:0
Number of H's:0 Number of I's:1 Number of J's:0 Number of K's:0 Number of L's:0 Number of M's:0 Number of N's:0
Number of O's:0 Number of P's:0 Number of Q's:0 Number of R's:0 Number of S's:0 Number of T's:0 Number of U's:0
Number of V's:0 Number of W's:1 Number of X's:0 Number of Y's:0 Number of Z's:0 Number of a's:20 Number of b's:1
Number of c's:3 Number of d's:8 Number of e's:28 Number of f's:8 Number of g's:6 Number of h's:12 Number of i's:11
Number of j's:0 Number of k's:4 Number of l's:4 Number of m's:6 Number of n's:22 Number of o's:22 Number of p's:3
Number of q's:0 Number of r's:16 Number of s's:17 Number of t's:29 Number of u's:10 Number of v's:1 Number of w's:9
Number of x's:0 Number of y's:6 Number of z's:0