Search code examples
javastringreplaceall

How to remove multiple words, Not replace!, 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.

The replacement doesn't work as it deletes a part of a word.

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

Output:

Hello
The Athens in
Th cat

Solution

  • 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(" +", " ");
        }
    }