如何从字符串中删除多个单词 Java

How to remove multiple words 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" }));
    }
}

class WordDeleter {
    public String remove(String phrase, String[] words) {
        String[] array = phrase.split(" ");
        String word = "";
        String result = "";

        for (int i = 0; i < words.length; i++) {
            word += words[i];
        }
        for (String newWords : array) {
            if (!newWords.equals(word)) {
                result += newWords + " ";
            }
        }
        return result.trim();
    }
}

输出:

Hello
The Athens is in Greece

我已经尝试过在这里使用 replace,但是没有用。

程序员经常这样做:

String sentence = "Hello Java World!";
sentence.replace("Java", "");
System.out.println(sentence);

=> 你好 Java 世界

字符串是不可变的,替换函数returns一个新的字符串对象。所以改为写

String sentence = "Hello Java World!";
sentence = sentence.replace("Java", "");
System.out.println(sentence);

=> 你好,世界!

(空白仍然存在)

有了它,你的替换函数看起来像

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

您可以使用流来完成:

String phrase = ...;
List<String> wordsToRemove = ...;
        
String result = Arrays.stream(phrase.split("\s+"))
     .filter(w -> !wordsToRemove.contains(w))
     .collect(Collectors.joining(" "));