Remove specific substring from string in C++

In this tutorial, we will learn how to remove some specific substring from a given string using inbuilt functions of the string library in the C++ programming language.

#include <iostream>
#include <string>
int main() {
    std:: string original ="how are you.";
    std:: string substring = "are";
    
    std::size_t ind = original.find(substring); // Find the starting position of substring in the string
    if(ind !=std::string::npos){
        original.erase(ind,substring.length()); // erase function takes two parameter, the starting index in the string from where you want to erase characters and total no of characters you want to erase.
        std::cout<<original<<"\n";
    }else{
        std::cout<<"Substring does not exist in the string\n";
    }
    return 0;
}

 

Code explanation

  • In this code we have used two built-in functions that are std::string::find() and std::string::erase() from string library.
  • std::string::find()  is used to find the starting index of a substring in the original string.
  • std::string::erase() is used to erase the substring from the original string. 
  • First with the help of a string.find() statement we found the starting position of the substring in the original string.
  • If substring does not exist in the original string then string.find() will return std::string::npos.
  • Inside if condition we have used string.erase() function to erase the substring.
  • String.erase() takes 2 parameters i.e. the starting index from where data has to be erased and the number of characters to be deleted.

 

how you.

In the code our original string is “how are you” and the substring is “are” so after removing the substring we are getting “how you” as output.

Leave a Reply

Your email address will not be published.