有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java替换方法无法正常工作

您好,我有一个字符串,当我尝试在for循环中使用replace方法时,它不起作用

String phrase="hello friend";
String[] wordds=phrase.split(" ");
String newPhrase="sup friendhello weirdo";
for (int g=0;g<2;g++)
{          
   finalPhrase+=newPhrase.replace(wordds[g],"");
}   
System.out.println(finalPhrase);

它打印出sup hello weirdo,我希望它打印出sup weirdo

我做错了什么


共 (5) 个答案

  1. # 1 楼答案

    除了立即修复的建议外,还可以考虑基于正则表达式的解决方案,没有循环:

    String phrase="hello friend";
    String regex=phrase.replace(' ', '|');
    String newPhrase="sup friendhello weirdo";
    String finalPhrase=newPhrase.replaceAll(regex,"");
    System.out.println(finalPhrase);
    

    或者更简洁地说:

    System.out.println("sup friendhello weirdo"
                       .replaceAll("hello friend".replace(' ','|'), 
                                   ""));
    
  2. # 2 楼答案

    让我们一起调试它

    wordds = ["hello", "friend"]

    newPhrase = "sup friendhello weirdo"

    然后你在一些g上运行从01(应该是从0wordds.length

    newPhrase.replace(wordds[g],"");确实会根据您的需要进行替换,但在调试程序时,您会注意到您使用的是+=而不是:

    newPhrase=newPhrase.replace(wordds[g],"");
    

    生活提示:使用调试器,它会帮助你

  3. # 3 楼答案

    你要做的是,把替换的短语附加到另一个短语上

    newPhrase = newPhrase.replace(wordds[g],"");
    
  4. # 4 楼答案

    试试这个:

    String phrase = "hello friend";
    String[] wordds = phrase.split(" ");
    String newPhrase = "sup friendhello weirdo";
    for (int g = 0; g < 2 ; g++) {          
      newPhrase = newPhrase.replace(wordds[g], "");
    }   
    System.out.println(newPhrase);
    

    ====================================================================================

    已更新

    你需要纠正的事情很少

    1. 当你试图替换一个句子中的特定单词时,你需要删除concatoprator(+)。只需在更换后分配即可

    2. 每次进入循环时,您都要使用初始声明的字符串,而需要使用每次更新的字符串

  5. # 5 楼答案

    这应该可以做到:

    String phrase="hello friend";
    String[] wordds=phrase.split(" ");
    String newPhrase="sup friendhello weirdo";
    String finalPhrase=newPhrase;
    for (int g=0;g<wordds.length;g++)
    {          
       finalPhrase=finalPhrase.replace(wordds[g],"");
    }   
    System.out.println(finalPhrase);
    

    首先,为新短语指定最终短语。然后迭代所有拆分的单词(我已经将神奇常数2更改为拆分单词数wordds.length。最终短语字符串中的每个单词都将被替换。生成的字符串看起来像sup weirdo(单词之间有两个空格)

    可以使用answer from here清理额外的空间:

    System.out.println(finalPhrase.trim().replaceAll(" +", " "));