替换方法无法正常工作

时间:2013-11-03 15:51:57

标签: java string replace

你好我有一个字符串,当我尝试在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 个答案:

答案 0 :(得分:5)

让我们一起调试。

wordds = ["hello", "friend"]

newPhrase = "sup friendhello weirdo"

然后,您正在从g0的某些1上运行(应该是0wordds.length

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

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

终身提示:使用调试器,它可以帮助您。

答案 1 :(得分: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. 当您尝试替换句子中的特定单词时,需要删除concat oprator(+)。只需在替换

  2. 后分配即可
  3. 每次进入循环时,您将获取初始声明的字符串,而不是每次都需要使用更新的字符串

答案 2 :(得分:1)

你在做什么,是将被替换的短语附加到另一个

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

答案 3 :(得分: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(' ','|'), 
                               ""));

答案 4 :(得分:0)

这应该可以解决问题:

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

首先,将finalPhrase指定给newPhrase。然后你迭代所有分裂的单词(我已经将你的魔法常量2改为分词wordds.length的数量。每个单词都将被替换为finalPhrase字符串。结果字符串看起来像{{1} (单词之间有两个空格)。

您可以使用answer from here

清理多余的空格
sup  weirdo
相关问题