下面的代码应该根据以下原则计算字符串中的音节:
我的代码执行前两个规则,但不执行最后一个规则。是否有人可以帮助我修改此代码以满足第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;
}
答案 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
}