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

时间:2014-12-21 19:00:04

标签: java string

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

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 个答案:

答案 0 :(得分:1)

您可以使用regular expression

执行此操作
s1 = s1.replaceAll("\\b(is|on|of|with)\\b","");

那会删除单词,但是留下两边的空格,所以之后你可能想用单身替换双空格:

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