Given a string and a word, the task of removing the word from this string, if any, returns -1 as output. For more details, see the following image.
Illustration:
Input : This is the Geeks For Geeks word="the" Output : This is Geeks For Geeks Input : Hello world Hello" word = Hello Output : world Explanation: The given string contains the word two times Input : Hello world word = GFG Output : Hello world Explanation: word doesn't exists in the string
To achieve this goal, we will now discuss two approaches, which are as follows:
Method 1: Using searching techniques
Example
// Java Program to Remove a Given Word From a String // using searching techniques // Importing input output classes import java.io.*; // main class class GFG { // Method 1 // To remove the word static void remove(String str, String word) { // Split the string using split() method String msg[] = str.split(" "); String new_str = ""; // Itearating the string using for each loop for (String words : msg) { // If desired word is found if (!words.equals(word)) { // Concate the word not equal to the given // word new_str += words + " "; } } // Print the new String System.out.print(new_str); } // Method 2 // Main driver method public static void main(String[] args) { // Custom string as input String str = "This is the Geeks For Geeks"; // Word to be removed from above string String word = "the"; // Calling the method 1 by passing both strings to // it remove(str, word); } }
Output
This is Geeks For Geeks
Method 2: Using String.replaceAll() Method
Example
// Java Program to Remove a Given Word From a String // Importing input output classes import java.io.*; // Main class class GFG { // Main driver method public static void main(String[] args) { // Given String as input from which // word has to be removed String str = "This is the Geeks For Geeks"; // Desired word to be removed String word = "the"; // Replace all words by "" string // using replaceAll() method str = str.replaceAll("the", ""); // Trim the string using trim() method str = str.trim(); // Printing the final string System.out.print(str); } }
Output
This is Geeks For Geeks