java - 如何查看有多少个以a、b、c、d等开头的单词?

标签 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);

最佳答案

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]);
        }
    }

关于java - 如何查看有多少个以a、b、c、d等开头的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35868910/

相关文章:

java - 在 Android 中加密并在 CryptoJS 中解密

c# - 在 Powershell 中替换字符串的一部分

java - 在字符串末尾添加随机字符?

mysql - MARIADB - 如果未提供默认值,SQL 能否将 NULL 转换为空字符串?

Java - 访问静态方法 sleep - 怎么了?

java - 如何在 grails 3+ 中启用 webapp 可分发

java - 如何在java中访问Window Phone驱动器路径以在手机驱动器上读写

java - 在带有 dp 的 relativeLayout 中使用布局参数

python - 检测空格并应用于变量

java - 需要正则表达式模式来获取介于两者之间的所有内容