Java 替换字符串中的特定单词,给定单词所在位置索引的arraylist
我有这两个方法,一个“findFour”查找给定字符串中所有“坏单词”的索引。它将找到的坏单词的索引放入arrayList并返回它。下一个方法“replaceFour”将在相同的给定字符串中找到这些相同的坏单词,然后用“$$$”之类的符号替换这些单词并返回字符串。例如,如果我的输入字符串是“Oh dang that's crap”,那么findFour方法将返回一个带有[3,13](这是两个“坏”字的索引)的arrayList,然后replaceFour方法将返回“Oh$$$$$$这是$$$$$$$”,我正在尝试弄清楚如何基本上生成replaceFour方法Java 替换字符串中的特定单词,给定单词所在位置索引的arraylist,java,Java,我有这两个方法,一个“findFour”查找给定字符串中所有“坏单词”的索引。它将找到的坏单词的索引放入arrayList并返回它。下一个方法“replaceFour”将在相同的给定字符串中找到这些相同的坏单词,然后用“$$$”之类的符号替换这些单词并返回字符串。例如,如果我的输入字符串是“Oh dang that's crap”,那么findFour方法将返回一个带有[3,13](这是两个“坏”字的索引)的arrayList,然后replaceFour方法将返回“Oh$$$$$$这是$$$$$
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++){
}
}
public ArrayList findFour(字符串文本){
对于(inti=0;i您可以使用基本的字符串操作,比如使用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);
使用字符串。替换()使用列表尝试此解决方案
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"));
}
静态列表有害词=null;
公共静态字符串replaceBadWords(字符串s){
List lsStr=Arrays.asList(s.split(“”);
列表结果=新建ArrayList();
用于(字符串sr:lsStr){
如果(包含坏词(sr)){
sr=“$$”;
}
结果:添加(sr);
}
返回字符串。join(“,result);
}
公共静态void main(字符串[]args){
坏词=新数组列表();
坏话。加上(“废话”);
坏话。添加(“当”);
System.out.println(替换脏话(“噢,该死,那是废话”);
}
你的问题是什么?哦,糟糕,我编辑了标题谢谢你,我已经在这上面呆了一段时间了。
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"));
}