java - 我如何使这个审查单词的代码起作用?

标签 java string

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

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/

相关文章:

java - 使用 for 循环调用多个方法?

java - Java ftps连接,TrustManager说明(使用Filezilla服务器)

java - vaadin & Spring 启动 : compiled widgetset is missed in jar package

java - Jackson + reSTLet + tomcat - 无法注册助手 org.reSTLet.ext.jackson.JacksonConverter

c - 使用 gdb 调试我的字符串分词器

c# - 在两种语言通用的 Java 和 C# 中生成 key

string - 如何在 Dart 语言中按字母顺序对字符串列表进行排序?

使用 strtol 和指针将字符串转换为 long

ios - 我创建了一个字符串扩展以在 swift 2.0 中将字符串与空格连接起来,但它在 swift 2.1 xcode 7 中不起作用

c - 有人知道 atolf c 函数吗?