我正在做我书中的练习,但它只部分起作用。它适用于我要审查的三个词之一。我不知道为什么会这样。这是代码:
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
获得 *
的计数,但我不知道如何使用它。
最佳答案
您不是在累积替换,而是仅将最后一个替换分配给 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(',', '|'), "***");
关于java - 我如何使这个审查单词的代码起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223458/