我正在从我的书中进行练习,但它只能部分起作用。它适用于我想要审查的三个单词之一。我不知道它为什么会这样。这是代码:
public static void main(String[] args){
String text = "Microsoft announced its next generation Java compiler today. It uses advanced parser and special optimizer for the Microsoft JVM.";
String forbiddenWords = "Java,JVM,Microsoft";
String[] words = forbiddenWords.split(",");
String newText = "";
for(String word: words){
System.out.println(word);
}
for(int i = 0; i < words.length; i++){
newText = text.replaceAll(words[i], "***");
}
System.out.println(newText);
}
这就是我得到的答案:
*** announced its next generation Java compiler today. It uses advanced parser and special optimizer for the *** JVM.
我还必须用正确数量的*
审查它,但我不知道如何。我知道我可以通过使用*
得到words[i].length
s的数量,但我不知道如何利用它。
你没有积累替代品,而只是将最后一个替换品分配给newText
。而不是使用newText
,只需将新字符串分配给text
变量。
for (String word : words) {
text = text.replaceAll(word, "***");
}
System.out.println(text);
另外,如注释中所述,请注意replaceAll
实际上需要正则表达式,因此如果要替换的字符串包含任何正则表达式控制字符,则可能会失败。相反,你应该只使用replace
,它也将替换所有匹配的子串。
如果你想让*
的数量与单词的长度相匹配,你可以使用this technique:
for (String word : words) {
String xxx = new String(new char[word.length()]).replace("\0", "*");
text = text.replace(word, xxx);
}
System.out.println(text);
输出:
********* announced its next generation **** compiler today. It uses advanced parser and special optimizer for the ********* ***.
说到正则表达式,你实际上也可以使用replaceAll
和正则表达式覆盖所有禁用词,通过用,
替换|
(假设这些词不包含正则表达式控制字符)。
String forbiddenWords = "Java,JVM,Microsoft";
text = text.replaceAll(forbiddenWords.replace(',', '|'), "***");