【问题标题】:How to remove a sub string from a string in java [duplicate]如何从java中的字符串中删除子字符串[重复]
【发布时间】:2015-02-19 23:04:46
【问题描述】:

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

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"

我是编程新手,所以请考虑一下。

【问题讨论】:

标签: java string


【解决方案1】:

您可以使用regular expression

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

这将删除单词,但在两边留下空格,所以之后你可能想用单引号替换双空格:

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

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多