How to remove a given word from a string in Java

1 Answer

0 votes
public class MyClass {
    public static String removeWord(String str, String word) {
        if (str.contains(word)) {
            String tmp = word + " ";
            str = str.replaceAll(tmp, "");
            tmp = " " + word;
            str = str.replaceAll(tmp, "");
        }
        
        return str;
    }
    public static void main(String args[]) {
        String str = "java c c++ c# python rust go";
        String word = "rust";
 
        str = removeWord(str, word);
 
        System.out.println(str);
    }
}



/*
run:

java c c++ c# python go

*/

 



answered Nov 19, 2022 by avibootz
...