所以这就是我想要做的。我拿一个给定的字符串,并创建一个新的字符串。新的字符串将与原始字符串相同,但会使辅音翻倍。例如,rabbit
变成rrabbitt
等等。它只会使尚未加倍的辅音翻倍。检查一个字符串是否有元音,并创建一个新的字符串,使辅音加倍
这是我到目前为止有:
// Returns a new string in which all consonants in the given string are doubled.
// Consonants that are already doubled are not doubled again.
// For example, doubleConsonants("rabbit") returns "rrabbitt".
// It is assumed that in the given string is alphabetic and that no character
// appears more than twice in a row.
// Parameters:
// s - given string
// Returns new string with all consonants doubled
----------------------------------------------------------------------------
public static String doubleConsonants(String s) {
String newString = "";
String vowels = "aeiouAEIOU";
for (int i = 0; i < s.length(); i++) {
boolean hasVowel = false;
for (int n = 0; n == 10; n++){
if (vowels.charAt(n) == s.charAt(i)) {
newString += s.charAt(i);
i++;
hasVowel = true;
break;
}
}
if (hasVowel = false && s.charAt(i) != s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)) {
newString += s.charAt(i);
i++;
}
else if (hasVowel = false) {
newString += s.charAt(i);
i++;
}
}
return newString;
}
显然有一些问题与“死代码”和布尔hasVowels是“不使用”。我在搞什么?
您的for循环从不起作用。用for(int n = 0; n == 10; n ++)。 for循环只在条件n == 10是真的时才起作用,永远不会。 – Moonstruck
我以为n = 0是开始点,n == 10是结束... – Muldawg2020
我该如何改变它,所以它会经历10次迭代? – Muldawg2020