How to remove a given word from a string in java

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:

  1. Naive approach with search technique
  2. Optimal approach with String.replaceAll() method

Method 1: Using searching techniques 

  1. Convert the string into a string array.
  2. Iterate the array and check the word not adequate to the given word.
  3. Concatenate the word into a replacement string array name as a replacement string.
  4. Print the new string.

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 

  1. This method takes two inputs old_word and new word in regex format.
  2. Replace all old_word with new words.
  3. Returns the resulting string.

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

 

Submit Your Programming Assignment Details