【发布时间】:2018-04-04 01:16:57
【问题描述】:
如果它们跟随元音,我需要这个程序用 h 替换所有 r。 这只是一个测试程序,我的实际任务是将“Jaws”脚本中的所有 r 替换为跟随元音的 h,并对该字符串执行其他各种任务。
public static void main(String[] args) {
String s = "Hey, I'm from boston. harbor, fotter, slobber, murder.";
System.out.println(replace(s));
}
//this method should replace r with h if it follows a vowel.
public static String replace(String s) {
String newS = "";
String vowels ="aeiouAEIOU";
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == 'r' && isVowel(s.charAt(i-1))) {
newS = s.replace("r", "h");
}
}
return newS;
}
//this method will check if a character is a vowel or not.
public static Boolean isVowel(char s) {
String vowels="aeiouAEIOU";
if (vowels.contains("" + s)) {
return true;
}
return false;
}
}
【问题讨论】:
-
您的代码会产生什么而不是预期的输出,您是否使用断点和/或 System.out.println-Statements 调试过您的代码?
-
使用调试器找出发生了什么
-
replace将替换所有出现的而不是特定的 -
@Pavneet_Singh 的意思是
newS = s.replace("r", "h")将用"h"替换所有出现的"r",正如here 解释的那样。 -
抱歉忘记提及。我的代码目前将所有 r 替换为 h,而不管它们之前是什么字符。我会尝试调试器。是否有一个 String.replace 函数只会替换特定的事件而不是全部?