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

Time:05-20

Hi guys! 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

CodePudding user response:

Consider using replace or 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) represents that all fragment space is

CodePudding user response:

ReplaceAll uses a regex so you do not need a loop. Instead make an or regex out of the words array.

result = phrase.replaceAll("\\W(" String.join("|", words) ")\\W","");

CodePudding user response:

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