Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove multiple words from a string Java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading