In this article we will discuss how to remove single or multiple sub strings from a given string.

std::string class provides a member function string::erase() to remove some characters from a given position i.e.

It accepts a position and length of characters to be deleted from that position. It removes those characters from string object and also returns the updated string.

Let’s use this string::erase() function to remove sub strings from a string i.e.

Remove First Occurrence of given substring from main string

Let’s remove first occurrence of sub string “this” from string “Hi this is a sample string is for is testing. this is it .”.

To remove first occurrence of sub string only then we need to search it’s position and use string::erase() to remove it from string i.e.

Remove all Occurrences of given substring from main string.

Let’s remove all occurrences of sub string “is” from string “Hi this is a sample string is for is testing. this is it .”.

To remove all occurrence of a sub string, we need to search it’s position in loop until it’s not found and for each occurrence we need to use string::erase() to remove it from string.

Erase all Occurrences of all given sub strings from main string using C++11

Let’s remove all occurrences of 3 sub strings i.e. “for”, “is” and “testing” from string “Hi this is a sample string is for is testing. this is it .”.

Iterate over the vector of given sub string and for each one erase all occurrences of it from string.

Erase all Occurrences of all given sub strings from main string using Pre C++11 stuff

Complete example is as follows,

Output

 

 

Click Here to Subscribe for more Articles / Tutorials like this.