Remove word from string java – Java Program to Delete a Word from Sentence

Remove word from string java: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Java Program to Delete a Word from Sentence

  • Java program to delete a word from sentence using replaceAll() method.

In this java program, we have to remove a word from a string using replaceAll method of String class. Deleting a word from a sentence is a two step process, first you have to search the word the given sentence. Then you have to delete all characters of word from string and shift the characters to fill the gap in sentence.
For Example,
Input Sentence : I love Java Programming
Word to Delete : Java
Output Sentence : I love Programming

Java program to delete a word from a sentence

In this program, we will use replaceAll() method of String class, which replaces the each occurrence of given word in sentence with “”. Hence deleting the word from sentence.
Java program to delete a word from a sentence

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to Delete Vowels from String
 */
public class DeleteWordFromSentence {
    public static void main(String args[]) {
        String sentence, word;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter a Sentence");
        sentence = scanner.nextLine();
 
        System.out.println("Enter word you want to delete from Sentence");
        word = scanner.nextLine();
        // Deleting word from
        sentence = sentence.replaceAll(word, "");
 
        System.out.println("Output Sentence\n" + sentence);
    }
}

Output

I love Java Programming
Enter word you want to delete from Sentence
Java
Output Sentence
I love  Programming