The C + + implementation of a given string to delete the given string idea is mainly implemented in such several ways:
1.KMP algorithm
2. Use the STL string's find and then use the erase
3. Use C's strstr to find the string position, and then write to the new string with strncpy
4. Use the Boost library to use regular expressions
The complete code that has been tested:
The first method:
#include <iostream> #include <string>using namespace std;void deletestr (const char *STR, const char* SUB_STR, char *result); int main () {char Str[100],sub[100];cin>>str;cin>>sub;char result;deletestr (str,sub,& result); return 0;} void Deletestr (const char *STR, const char* sub_str, char *result) {int sublen = 0; Gets the length of the substring const char *t = SUB_STR; while (*t++! = ') ') {sublen++; } int pos = 0; int pp = 0; int repos = 0; The index of the result substring while (* (str + pos)! = ' + ') {char t = * (str + pos); if (t = = * (Sub_str + PP))//Repeat substring start position {* (result + repos) = t; repos++; if (pp < sublen-1)//not fully duplicated {pp++; } else if (pp = = sublen-1)//completely repeats {pp = 0; Repos-= Sublen; Backtrack subscript Position}} else{//Not the same character * (result + repos) = t; repos++; } pos++; } * (Result + repos) = ' + '; cout<<result<<endl;}
The second method, using the STL
Personal feeling is very simple and convenient
#include <iostream> #include <string>using namespace std;void deletesub (String &str,const string & Sub,int n); int main () { string str,sub;cin>>str;cin>>sub;int n=sub.size ();d eletesub (str,sub,n); return 0;} void Deletesub (String &str,const string &sub,int n) {int m,flag=0,num=0; Num is the number of occurrences of a substring while (flag==0) {m=str.find (sub); if (m<0) flag=1;else{ str.erase (m,n); Delete substring num++;} } cout<<num<<endl; Number of substring occurrences cout<<str<<endl; Output the deleted string }
Two implementations of C + + DELETE string