gpt4 book ai didi

Java - 计算字符串中的元音

转载 作者:行者123 更新时间:2023-11-29 04:54:39 24 4
gpt4 key购买 nike

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

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

最佳答案

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

关于Java - 计算字符串中的元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34233617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com