13

How to remove all instances of the pattern from a string?

string str = "red tuna, blue tuna, black tuna, one tuna";
string pattern = "tuna";
4
  • 3
    have to tried anything ? Commented Sep 7, 2015 at 9:12
  • 1
    The C++ standard library now include regular expressions including facilities to replace matches (and to remove, replace with an empty string). Commented Sep 7, 2015 at 9:19
  • Remove all substrings: str.clear() Commented Sep 7, 2015 at 9:30
  • 1
    boost::algorithm::erase_all(str, pattern); Commented Oct 17, 2019 at 8:27

5 Answers 5

17

Removes all instances of the pattern from a string,

#include <string>
#include <iostream>

using namespace std;

void removeSubstrs(string& s, string& p) { 
  string::size_type n = p.length();
  for (string::size_type i = s.find(p);
      i != string::npos;
      i = s.find(p))
      s.erase(i, n);
}

int main() {

  string str = "red tuna, blue tuna, black tuna, one tuna";
  string pattern = "tuna";

  removeSubstrs(str, pattern);
  cout << str << endl;
}
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't deal reasonably with overlapping patterns.
@Cheersandhth.-Alf what do you mean by overlapping patterns?
@AbhinavGauniyal: Remove all instances of "aha" from "shahaha". I think both "sh𝕒𝕙𝕒ha" and "shah𝕒𝕙𝕒" should be removed.
removeSubstrs needs check for emptiness of 'string &p'.
12

This is a basic question and you'd better take a look at the string capabilities in the standard library.

Classic solution

#include <iostream>
#include <string>

int main() { 
   std::string str = "red tuna, blue tuna, black tuna, one tuna";
   std::string pattern = "tuna";

   std::string::size_type i = str.find(pattern);
   while (i != std::string::npos) {
     str.erase(i, pattern.length());
     i = str.find(pattern, i);
   }

   std::cout << str;
}

Example

RegEx solution

Since C++11 you have another solution (thanks Joachim for reminding me of this) based on regular expressions

#include <iostream>
#include <string>
#include <regex>

int main() { 
   std::string str = "red tuna, blue tuna, black tuna, one tuna";
   std::regex pattern("tuna");

   std::cout << std::regex_replace(str, pattern, "");
}

Example

Comments

3

Try something like:

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}

From Replace part of a string with another string

Comments

1

A faster algorithm building the string one character at a time and checking if the end matches the substring. The following runs in o(substring * string) where as the above solutions run in o(s^2/t).

string S, T;
  cin >> S >> T;

  /* Build R, the result string, one character at a time. */
  string R;
  for (int i = 0; i < S.size(); i++) {
    R += S[i];

    /* If the end of R matches T then delete it. */
    if (R.size() >= T.size() && R.substr(R.size() - T.size()) == T) {
      R.resize(R.size() - T.size());
    }
  }

  cout << R << endl;

Comments

0

This is the basic logic for better understanding Here is the code in c++

    string s,x;                //s is the string , x is the substring
    int a,l; 
    cin>>s>>x;
    l=x.length();
    while(true)
    {
        a=s.find(x);
        if(a==-1)
        {break;}                       // if substring is not found
        else
        {
        s.erase(a,l);                  //if substring is found 
        }
    }
    if(s.length()==0)                  // if string length becomes null printing 0 
        cout<<0<<"\n";      
    else 
        cout<<s<<endl;                 // else printing the string

example: input-shahaha output-shha

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.