无法让 String.replace() 替换字符串中唯一的某些字母



我需要这个程序将所有r替换为h,如果它们跟随元音。这只是一个测试程序,我的实际任务是将"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;
    }
}

请使用字符串生成器在特定索引处替换 如前所述 替换字符串中特定索引处的字符?下面是替换方法的外观

public static String replace(String s) {
StringBuilder myName = new StringBuilder(s);
for (int i = 1; i < s.length(); i++) {
  if (s.charAt(i) == 'r' && isVowel(s.charAt(i - 1))) {
    myName.setCharAt(i, 'h');
  }
}
return myName.toString();

}

最新更新