如何从字符串 Java 中删除多个单词,而不是替换!

How to remove multiple words, Not replace!, from a string Java

我是 java 的新手,目前正在学习字符串。

如何从字符串中删除多个单词?如果有任何提示,我会很高兴。

替换不起作用,因为它删除了单词的一部分。

class WordDeleterTest {
    public static void main(String[] args) {
        WordDeleter wordDeleter = new WordDeleter();

        // Hello
        System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));

        // The Athens in
        System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));

        // This cat
        System.out.println(wordDeleter.remove("This is cat", new String[] { "is" }));
    }
}

class WordDeleter {
    public String remove(String phrase, String[] words) {
        String result = phrase;
        for (String word : words) {
            result = result.replace(word, "");
        }
        return result.trim();
    }
}

输出:

Hello
The Athens in
Th cat

ReplaceAll 使用正则表达式,因此您不需要循环。而是从单词数组中创建一个 or 正则表达式。

result = phrase.replaceAll("\W("+String.join("|", words)+")\W","");
class WordDeleter {
    public String remove(String phrase, String[] words) {
        String result = phrase;
        for (String word : words) {
            result = result.replaceAll("\b" + word + "\b", "");
        }
        return result.trim().replaceAll(" +", " ");
    }
}

考虑使用 replace 或 replaceAll with regexp

public static void main(String[] args) {
        String originalstring = "This is cat";
        System.out.println ("Original String: " + originalstring);
        System.out.println ("Modified String: " + originalstring.replaceAll("\s(is)", ""));
    }

\s(is)表示所有片段space+都是