In: Computer Science
C++ programming,How to remove element from string without using the string::erase() function ?
example:
input string:"cheasggaa"
element need to be removed:"ga"
output:"cheasga"
or:
input:"cekacssdka"
element:"ka"
output:"cecssd"
//C++ program
#include<iostream>
#include<string.h>
using namespace std;
int search(string pattern, string text)
{
int m = pattern.length();
int n = text.length();
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++)
if (tolower(text.at(i+j)) != pattern.at(j)) break;
if (j == m)
return i;
}
return -1;
}
void replace ( string & s , string text){
while(1){
int index=search(text,s);
if(index==-1)return;
s.replace(index, text.length(),
"");
}
}
int main(){
string str,text;
cout<<"input string: ";
getline(cin,str);
cout<<"element need to be removed : ";
cin>>text;
replace(str,text);
cout<<str;
return 0;
}
//sample output
