C++ Program to Delete a Word from Sentence

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

#include <iostream>
#include <cstring>
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;
Enter a string
I love C++ programming
Enter string to remove
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.

Recommended Posts
C++ Program to Convert Uppercase to Lowercase Characters
C++ Program to Print Array in Reverse Order
C++ Program to Delete Spaces from String or Sentence
C++ Program to Check whether a string is Palindrome or Not
C++ Program to Count Number of Vowels, Consonant, and Spaces in String
C++ Program to Find the Frequency of Characters in a String
C++ Program to Copy String Without Using strcpy
C++ Program to Convert Decimal Number to Binary Number
C++ Program to Check Strings are Anagram or Not
All C++ Programs