Find and replace in a sentence or string in C++

In this CPP tutorial, we are going to discuss how to find an all occurrence of a word in a sentence and replace it with a particular word at the place of every occurrence. This type of application we see in notepad, word pad etc. Commonly known as find and replace in C++.

How to read a sentence in CPP ?

In CPP, if we simply input a sentence using cin and getting its output using cout then it will show the characters only till first whitespace read after that characters it will ignore. So, to read whole sentence in CPP using just cin we use method as coded below:-

Ex:-

  string s;

                                            cin>>s;     // read whole sentence

                                              while(cin>>s)

                                         {



                                              cout<<s<<” “;

                                         }

Step by Step Approach

  • Read a string “s” using cin and input the string to be replaced and string to which it should be replaced.
  • Read the whole string using while(cin>>s) method.
  • Check while reading the string that if the word is same as to the replacing word then cout the word to be replaced else cout “s”.

C++ Code to find and replace in a string

#include<bits/stdc++.h>
using namespace std;

 int main()
{
    string s,s1,s2;
      cin>>s;
      
      cout<<"Enter the word to be replaced"<<endl;
        cin>>s1;
        
       cout<<"Enter the word to which it should be replaced"<<endl;
         cin>>s2;
         
         cout<<"Sentence before replacing :"<<endl;
         
           cout<<s<<" ";
           
           while(cin>>s)
           {
               cout<<s<<" ";
           }
           
           cout<<"Sentence after replacing :";
      
      if(s==s1)
      cout<<s2<<" ";
      
      else
        cout<<s<<" ";
      
      while(cin>>s)
      {
           if(s==s1)
          cout<<s2<<" ";
          
          else
            cout<<s<<" ";
      }
     
}

OUTPUT

Which site should i prefer for learning programming concepts. Which site is the best site for day to day programming blogs.

Enter the word to be replaced
Which 

Enter the word to which it should be replaced
Codespeedy

Sentence before replacing :
Which site should i prefer for learning programming concepts. Which site is the best site for day to day programming blogs.

Sentence after replacing :
Codespeedy site should i prefer for learning programming concepts. Codespeedy site is the best site for day to day programming blogs.

 

Thanks For Reading !!

Please, ask your doubts and for any suggestion comment in the comment section below.

Read other C++ tutorials,

Leave a Reply

Your email address will not be published. Required fields are marked *