简体   繁体   中英

How to remove multiple words from a string Java

I'm new to java and currently, I'm learning strings.

How to remove multiple words from a string?

I would be glad for any hint.

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();
    }
}

Output:

Hello
The Athens is in Greece

I've already tried to use replacе here, but it didn't work.

Programmers often do this:

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

=> Hello Java World

Strings are immutable, and the replace function returns a new string object. So instead write

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

=> Hello World!

(the whitespace still exists)

With that, your replace function could look like

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

You can do it using streams:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM