Java Program to Delete a Word from Sentence

Here is a 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.

package com.tcc.java.programs;

import java.util.Scanner;

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

Recommended Posts
Java Program to Delete all Vowel Characters from String
Java Program to Delete All Spaces from a String
Java Program to Count Words in a Sentence
Java Program to Reverse Sequence of Words of a Sentence
Java Program to Check Two Strings are Anagram or Not
Java Program to Concatenate Two Strings
Java Program to Find Length of a String
Java Program to Find Count of Each Character in a String
Java Program to Check Whether two Strings are Equal or Not
Java Program to Print Pyramid Pattern of Stars
Java Program to Print Pascal Triangle
All Java Programs