如何使此代码用于审查单词有效?

问题描述 投票:3回答:1

我正在从我的书中进行练习,但它只能部分起作用。它适用于我想要审查的三个单词之一。我不知道它为什么会这样。这是代码:

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].lengths的数量,但我不知道如何利用它。

java string
1个回答
10
投票

你没有积累替代品,而只是将最后一个替换品分配给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(',', '|'), "***");
© www.soinside.com 2019 - 2024. All rights reserved.