java 敏感词替换星号
时间: 2023-07-18 21:46:11 浏览: 110
好的,我可以帮你编写一个简单的敏感词过滤器,使用星号代替敏感词。以下是Java代码示例:
```
public class SensitiveWordFilter {
private static final String REPLACE_CHAR = "*";
private Set<String> sensitiveWords;
public SensitiveWordFilter(Set<String> sensitiveWords) {
this.sensitiveWords = sensitiveWords;
}
public String filter(String text) {
for (String sensitiveWord : sensitiveWords) {
String replaceString = getReplaceString(sensitiveWord.length());
text = text.replaceAll(sensitiveWord, replaceString);
}
return text;
}
private String getReplaceString(int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append(REPLACE_CHAR);
}
return stringBuilder.toString();
}
}
```
这个过滤器接受一个敏感词的Set作为构造函数参数,可以通过调用`filter`方法来过滤文本。过滤器会遍历所有敏感词,并使用`getReplaceString`方法生成相应长度的星号字符串来替换敏感词。
阅读全文