【问题标题】:Replacing words in a String java替换字符串java中的单词
【发布时间】:2013-12-01 03:39:58
【问题描述】:

假设我有一个字符串,

String templatePhrase = "I have a string that needs changing";

我还有一种方法可以替换任何给定字符串中的单词。方法如下:

public String replace(String templatePhrase, String token, String wordToPut) {

    return templatePhrase.replace(token, wordToPut);

}

现在说(为了我的实际任务)我将字符串str 中的所有单词都放在名为wordsInHashtags 的列表中。我想遍历wordsInHashtags 中的所有单词,并使用replace() 方法将它们替换为另一个名为replacement 的列表中的单词。每次循环迭代时,都应保存修改后的字符串,以便为下一个循环保存其替换。

如果有人想查看我的代码,我会发布我的代码,但我认为它会让人感到困惑,而不仅仅是帮助,我感兴趣的只是一种保存修改后的字符串以供循环的下一次迭代使用的方法。

【问题讨论】:

  • 继续发布您的代码
  • String temp=str; while(...) { temp = replace(temp, token, wordToPut); } 有什么问题
  • 吉姆·加里森 - 天才!这是漫长的一天......感谢您的帮助
  • 我认为问题在于,如果打算用“was”替换单词“is”,它不会将“kiss”更改为“kwass”,而您当前的代码会这样做: ,您编码的不是repkaceceords,而是字符序列,无论是否“单词”。另外,我会使用旧词-->新词的地图。

标签: java string replace


【解决方案1】:

前几天我刚开始阅读 Java 2 中的字符串:“字符串对象是不可变的”基本上不能更改,但是创建 StringBuffer 对象是为了处理我理解的这种情况。你可以试试:

StringBuffer templatePhrase = "I have a string to be changed";

templatePhrase.replace(token, wordToPut);

String replacedString = (String)templatePhrase;

第 3 行可能会导致问题?

【讨论】:

    【解决方案2】:

    公共类改写{

    public static void main(String[] args) {
    
        /***
         Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
         ********/
        String sentence = "I hate you";
        String replaceWord = " hate";
        String replacementWord = "love";
    
        int hateIndex = sentence.indexOf(replaceWord);
        String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
         System.out.println(fixed);
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-03
      • 2015-03-03
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      相关资源
      最近更新 更多