C++ Program to Delete a Word from Sentence

  • Write a C++ program to remove a word from a sentence.

Given a sentence and a word(may not be part of sentence), we have to delete given word from sentence and print it on screen. Given word may or may not be present in sentence.

For Example :
Input : I love C++ programming
Word to Remove : C++
Output : I love programming
Algorithm to Delete a Word from Sentence
  • Find the length of word. Let it be L.
  • Search word in sentence. If word is not present in sentence then print original sentence.
  • If we found word at index i, then copy string from index i+L to i. This will override all characters of word.
  • Print modified sentence on screen.

C++ Program to Delete Word from Sentence

//C++ Program to delete a word from a sentence
#include 
#include 
using namespace std;
 
int main(){
   char string[100], pattern[100];
   char *ptr;
   int length;
    
   cout << "Enter a string\n";
   cin.getline(string, 100);
   
   cout << "Enter string to remove\n";
   cin.getline(pattern, 100);
   // Find length of pattern
   length = strlen(pattern);
   // Search pattern inside input string 
   ptr = strstr(string, pattern);
   
   // Delete pattern from string by overwriting it 
   strcpy(ptr, ptr+length);
   
   cout << "Final String\n" << string;
    
   return(0);
}
Output
Enter a string
I love C++ programming
Enter string to remove
C++
Final String
I love  programming

In above program, we first take a sentence as input from user using cin. Then we ask user to enter word for deletion. Then we find the length of word using strlen function and store it in a variable length. Here we are using strstr function to search word inside sentence, If found we overwrite the characters of given word by shifting sentence by "length" positions.