How to remove all occurrences of word from a string in Java

3 Answers

0 votes
import java.util.regex.Pattern;

public class RemoveAllOccurrencesOfWordFromString_Java {
    public static void main(String[] args) {
        String s = "rust java c c++ java c# java golang python";
        String remove = "java";
        
        Pattern regex = Pattern.compile(remove);
        s = regex.matcher(s).replaceAll("");

        System.out.println(s);
    }
}


/*
run:

rust  c c++  c#  golang python

*/

 



answered Oct 13, 2024 by avibootz
0 votes
public class RemoveAllOccurrencesOfWordFromString_Java {
    public static void main(String[] args) {
        String s = "rust java c c++ java c# java golang python";
        String remove = "java";
        
        s = s.replaceAll(remove, "");

        System.out.println(s);
    }
}


/*
run:

rust  c c++  c#  golang python

*/

 



answered Oct 13, 2024 by avibootz
0 votes
public class Main {
    static String removeWord(String str, String word) {
        String[] words = str.toLowerCase().split(" ");
        String new_str = "";
 
        for (String s : words) {
            if (!s.equals(word)) {
                new_str += s + " ";
            }
        }
 
        return new_str;
    }
    public static void main(String[] args) {
        String s = "rust java c c++ java c# java golang python";
         
        s = removeWord(s, "java");
 
        System.out.println(s);
    }
}
 
 
/*
run:
 
rust c c++ c# golang python 
 
*/

 



answered Feb 2, 2025 by avibootz

Related questions

1 answer 182 views
1 answer 158 views
2 answers 141 views
2 answers 142 views
1 answer 125 views
...