有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中从字符串中删除子字符串

我需要预处理一个字符串并从中删除一些单词。我要找的是:-

private static final String[] stopWords = { "is", "on", "of", "with"};
String s1 = "Tiger is Mammal with sharp teeth";
System.out.println("s1 = " + s1);  // "Tiger is Mammal with sharp teeth"
s1.remove(stopWords);  //remove should remove 'is' and 'with'  from s1
System.out.println("s1 = " + s1); // "Tiger Mammal sharp teeth"
我对编程很陌生,所以请考虑一下。


共 (1) 个答案

  1. # 1 楼答案

    您可以使用regular expression来实现这一点:

    s1 = s1.replaceAll("\\b(is|on|of|with)\\b","");
    

    这将删除单词,但在两侧保留空格,因此在此之后,您可能希望将双空格替换为单空格:

    s1 = s1.replace("  "," ");