如何检查有多少单词以a,b,c,d等开头?

时间:2016-03-08 13:36:25

标签: java string

我有这个代码检查字母a,b,c,d等是否是单词中的第一个字母(在代码中称为'apple')。然后,它存储从每个字母开始的单词数。我试图简化我的代码,可能像使用for循环或数组,但我不知道如何。

int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0;

if(apple.length() > 0)
{
    if (apple.charAt(0) == 'a') {
        a++;
    }
    else if (apple.charAt(0) == 'b') {
        b++;
    }
    else if (apple.charAt(0) == 'c') {
        c++;
    }
    else if (apple.charAt(0) == 'd') {
        d++;
    }
    .
    .
    .
    else if (apple.charAt(0) == 'x') {
        x++;
    }
    else if (apple.charAt(0) == 'y') {
        y++;
    }
    else if (apple.charAt(0) == 'z') {
        z++;
    }
}

System.out.println("The number of words that start with a - " + a);
System.out.println("The number of words that start with b - " + b);
System.out.println("The number of words that start with c - " + c);
System.out.println("The number of words that start with d - " + d);
.
.
.
System.out.println("The number of words that start with x - " + x);
System.out.println("The number of words that start with y - " + y);
System.out.println("The number of words that start with z - " + z);

3 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {

        String apple = "apple";
        int[] arr = new int[26];
        String matchStr = "abcdefghijklmnopqrstuvwxyz";
        char[] charArr = matchStr.toCharArray();

        for(int i = 0 ; i < arr.length ; i ++) {
            if(apple.startsWith(charArr[i] + "")) {
                arr[i]+= 1;
            }
        }

        for(int i = 0 ; i < charArr.length ; i ++) {
            System.out.println("The number of words that start with " + charArr[i] + " - " + arr[i]);
        }
    }

答案 1 :(得分:0)

String apple = "some test string for stackoverflow";

Map<Character, Integer> charList = new HashMap<Character, Integer>();
for (char c = 'a'; c <= 'z'; ++c) {
    charList.put(c, 0);
}

Character first = apple.toLowerCase().charAt(0);
Integer count = charList.get(first);
if (count != null) {
    charList.put(first, ++count);
}

for (Entry<Character, Integer> entry : charList.entrySet()) {
    System.out.println("The number of words that start with "+entry.getKey()+" - " + entry.getValue());
}

答案 2 :(得分:0)

final int A = (int)'A';
final int Z = (int)'Z';
final int baseLen = Z - A;

final int a = (int)'a';
final int z = (int)'z';
final int upperToLower = a - Z;

final int totalLen = baseLen * 2;

int [] record = new int[totalLen];

for(String s : yourWordList)
{
    int start = (int)s.charAt(0);

    start = start - A;
    if(start > baseLen)
        start = start - upperToLower;

    record[start] += 1;
}

for(int i : record) {

    int base = i + A;
    if(i > baseLen)
        base += upperToLower;

    System.out.println("Num of " + (char)(i) + " is " + record[i]);
}