How to remove all substrings from a string

前端 未结 4 965
终归单人心
终归单人心 2020-12-01 23:56

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条回答
  •  囚心锁ツ
    2020-12-02 00:48

    Removes all instances of the pattern from a string,

    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题