How to remove all substrings from a string

前端 未结 4 962
终归单人心
终归单人心 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

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

    Classic solution

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

提交回复
热议问题