【问题标题】:Cannot get String.replace() to replace the only certain letters in string [duplicate]无法让 String.replace() 替换字符串中唯一的某些字母 [重复]
【发布时间】: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 函数只会替换特定的事件而不是全部?

标签: java replace


【解决方案1】:

Replace a character at a specific index in a string? 所说,请使用字符串生成器替换特定索引处 下面是您的替换方法的外观

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();

}

【讨论】:

  • 成功了,谢谢!
  • @John Antonio 请接受它作为答案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
相关资源
最近更新 更多