首页 > 解决方案 > 替换字符串中的特定单词,给定单词所在索引的数组列表

问题描述

我有这两种方法,一个“findFour”查找给定字符串中所有“坏词”的索引。它将定位到的坏词的索引放入一个arrayList并返回它。下一个方法“replaceFour”将在相同的给定字符串中找到那些相同的坏词,然后用“$$$$”之类的符号替换这些词并返回字符串。例如,如果我的输入字符串是“Oh dang that's crap”,那么 findFour 方法将返回一个带有 [3, 13] 的 arrayList(这是两个“坏”词的索引),那么 replaceFour 方法将返回“哦 $$$$ 那是 $$$$” 我想弄清楚如何基本上制作 replaceFour 方法。

public ArrayList<Integer> findFour(String text){
    for(int i=0; i<text.length()-4;i++){
        String fourLetter = text.substring(i, i+4);
        FourWords.add(fourLetter);
        if(fourLetter.equals(BadWords.get(0)) || fourLetter.equals(BadWords.get(1)) || fourLetter.equals(BadWords.get(2))){
            IndexofBad.add(i);
        }

    }
    return IndexofBad; //this arrayList contains index of all the bad words in the given string
}

//have to replace the bad words with a different text
public void replaceFour(String text){//Have not figured out
    newString.equals(text);
    for(int i=0; i<IndexofBad.size(); i++){

    }
}

标签: java

解决方案


使用String.replaceOracle 文档


推荐阅读