我有这两种方法,一个“ findFour”查找给定字符串中所有“坏词”的索引。它将找到的坏词的索引放入arrayList并返回它。下一个方法“ replaceFour”将在相同的给定字符串中找到那些相同的坏词,然后将这些单词替换为诸如“ $$$$”之类的符号并返回String。例如,如果我的输入String是“糟糕的当当”,那么findFour方法将返回带有[3,13](这是两个“坏”字的索引)的arrayList,然后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++){
}
}
答案 0 :(得分:1)
使用String.replace
(Oracle doc)
答案 1 :(得分:0)
您可以使用基本的String操作来完成此操作,例如使用indexOf()
和substring()
方法。
String s = "Oh crap that sucks";
List<Integer> badWordIndices = List.of(3, 13);
for (Integer i : badWordIndices) {
int indexOfNextSpace = s.indexOf(" ", i);
s = s.substring(0, i) + "$$$$" + (indexOfNextSpace != -1 ? s.substring(indexOfNextSpace) : "");
}
System.out.println(s);
输出
Oh $$$$ that $$$$
答案 2 :(得分:0)
使用List尝试此解决方案。
static List<String> badWords = null;
public static String replaceBadWords(String s) {
List<String> lsStr = Arrays.asList(s.split(" "));
List<String> result = new ArrayList<String>();
for(String sr: lsStr) {
if(badWords.contains(sr)) {
sr = "$$$";
}
result.add(sr);
}
return String.join(" ", result);
}
public static void main(String[] args) {
badWords = new ArrayList<>();
badWords.add("crap");
badWords.add("dang");
System.out.println(replaceBadWords("Oh dang that's crap"));
}