【问题标题】:Java - Counting the vowels in stringJava - 计算字符串中的元音
【发布时间】:2015-12-11 22:31:17
【问题描述】:

下面的代码应该根据以下原则计算字符串中的音节:

  1. 应将单个元音或一组元音计为一个音节。
  2. 如果一个单独的“e”位于字符串的末尾,并且字符串的其余部分有更多元音,则“e”不是一个音节。
  3. 如果一个单独的“e”在结尾,并且“e”旁边有一个或多个元音,并且字符串的其余部分也有更多元音,则“e”是一个音节。

我的代码执行前两条规则,但没有执行最后一条。有人可以帮助我修改此代码以同时满足第三条规则吗?

protected int countSyllables(String word) {
    String input = word.toLowerCase();
    int syl = 0;
    boolean  vowel  = false;
    int length = word.length();
    //check each word for vowels (don't count more than one vowel in a row)
    for(int i=0; i<length; i++) {
        if        (isVowel(input.charAt(i)) && (vowel==false)) {
            vowel = true;
            syl++;
        } else if (isVowel(input.charAt(i)) && (vowel==true)) {
            vowel = true;
        } else {
            vowel = false;
        }
    }
    char tempChar = input.charAt(input.length()-1);
    //check for 'e' at the end, as long as not a word w/ one syllable
    if ((tempChar == 'e')  && (syl != 1)) {
        syl--;
    }
    return syl;
}

【问题讨论】:

  • 在减去syl--之前必须先检查前一个字符中没有元音。
  • 您能给我们举个例子,说明第二种和第三种情况的有效输入和输出吗?

标签: java string for-loop charat


【解决方案1】:
protected int countSyllables(String word) {
    if(word.isEmpty()) return 0; //don't bother if String is empty

    word = word.toLowerCase();
    int      totalSyllables    = 0;
    boolean  previousIsVowel  = false;
    int      length = word.length();

    //check each word for vowels (don't count more than one vowel in a row)
    for(int i=0; i<length; i++) {
        //create temp variable for vowel
        boolean isVowel = isVowel(word.charAt(i));

        //use ternary operator as it is much simple (condition ? true : false)
        //only increments syllable if current char is vowel and previous is not
        totalSyllables += isVowel && !previousIsVowel ? 1 : 0;

        if(i == length - 1) { //if last index to allow for 'helloe' to equal 2 instead of 1
            if (word.charAt(length - 1) == 'e' && !previousIsVowel)
                totalSyllables--; //who cares if this is -1
        }

        //set previousVowel from temp 
        previousIsVowel = isVowel;
    }

    //always return 1 syllable
    return totalSyllables > 0 ? totalSyllables : 1;
}

【讨论】:

    【解决方案2】:

    在测试e 是否在末尾时,只需在删除音节之前添加一个条件。只需确保最后一个字符的字符不是元音即可。


    解决方案

    if ((tempChar == 'e')  && (syl != 1) && !isVowel(word.charAt(word.length()-2))) {
        syl--;
    }
    

    输出

    public static void main(String[] args) {
        System.out.println(countSyllables("Canoe"));  // 2
        System.out.println(countSyllables("Bounce")); // 1
        System.out.println(countSyllables("Free"));   // 1
    }
    

    【讨论】:

    • @LalehH 很高兴为您提供帮助!如果它对您有任何帮助,请不要忘记投票:)
    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 2018-04-30
    • 2020-02-19
    • 2011-09-05
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多