【发布时间】:2017-04-15 01:19:42
【问题描述】:
我必须编写一个方法,它接收一个字符串并返回一个复制所有元音的新字符串,并在其间添加一个“b”。唯一的例外是双音字,“ab”应该放在双音字前面。
例如:“hello”将返回“hebellobo” “听力”将返回“轴承”
我已经用我的代码试验了几个小时,但我什么也没做。 好吧,什么都没有,但不能让它在元音上正常运行,而且根本没有到达双元音。 这是我的代码:
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter a string: ");
String s = sc.nextLine();
String originalString = s;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i') || (c == 'O')
|| (c == 'o') || (c == 'U') || (c == 'u'))
{
String front = s.substring(0, i);
String back = s.substring(i + 1);
s = front + c + "b" + back;
}
}
System.out.println(originalString);
System.out.println(s);
}
感谢您的帮助!
感谢您的帮助,我现在有了以下代码(没有扫描仪):
public static boolean isVowel(char c) {
// TODO exercise 1 task b) part 1
if (c == 'a' || c == 'A' || c == 'Ä' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O'
|| c == 'Ö' || c == 'u' || c == 'U' || c == 'Ü') {
return true;
} else {
return false;
}
}
public static String toB(String text) {
// TODO exercise 1 task b) part 2
StringBuilder b = new StringBuilder();
for (int i = 0; i < text.length() - 1; i++) {
char current = text.charAt(i);
char next = text.charAt(i + 1);
if (isVowel(current)) {
if (isVowel(next)) {
// 1 - Is a vowel followed by a vowel
// Prepend b
b.append("b");
// Write current
b.append(current);
// Write next
b.append(next);
i++; // Skip next vowel
} else {
// 2 - Is a vowel followed by a consonant
b.append(current);
b.append("b");
b.append(current);
}
} else {
// 3 - Is a consonant
b.append(current);
}
}
for (int i = 0; i < text.length() - 1; i++) {
char last = text.charAt(text.length() - 1);
char current = text.charAt(i);
if (isVowel(last)) {
// Case 1
b.append(current);
b.append("b");
b.append(current);
// Case 2 is not possible for last letter
} else {
// Case 3
b.append(last);
}
}
// Here b.toString() is the required string
return b.toString();
}
例如,如果您输入单词“Mother”,则输出是“Mobotheberrrrr”,这很好,只是由于某种原因它重复了最后一个字母“r”。不幸的是,输入“Goal”会导致输出“Gboalll”。
【问题讨论】:
-
不应该是“habearibing”
-
你对
diphthong的解释是什么?是“任意”两个连续元音还是只有满足特定条件的两个连续元音? -
@Henry 你说的完全正确,抱歉 :)
-
@VHS 我对双元音的解释是以下元音 "au";"ai"; 的组合。 “ei”;“eu”;“ui”。
标签: java string char substring