Java - 用字符串计算元音

时间:2015-12-11 22:31:17

标签: java string for-loop charat

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

  1. 它应该将一个元音或一组元音统计为一个音节。
  2. 如果是孤独的" e"在字符串的末尾,字符串的其余部分有更多的元音,然后" e"不是音节。
  3. 如果是孤独的" e"最后,在" e"旁边有一个或多个元音。并且在其余的字符串中还有更多的元音,然后" e"是一个音节。
  4. 我的代码执行前两个规则,但不执行最后一个规则。是否有人可以帮助我修改此代码以满足第3条规则?

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

在测试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
}