Tuesday, March 29, 2011

WAP to Removing characters from an input string in place.

#include
#include
void removeLetters(std::string& s, const std::string& pattern)
{
bool searchArray[128] = {false};
int patternlen = pattern.length();
for(int i=0; i{
searchArray[pattern[i]] = true;
}

int len = s.length();
int vcount = 0;
int vstart = -1;

for(int i=0; i{
if(searchArray[s[i]])
{
if(vstart == -1)
vstart = i;
vcount++;
}

if(!searchArray[s[i]] && vstart != -1)
{
s[i] = s[i] + s[vstart];
s[vstart] = s[i] - s[vstart];
s[i] = s[i] - s[vstart];
vstart++;
}
}
s = s.substr(0, len-vcount);
}

int main(int argc, char** argv)
{
std::string s = "the rain in spain is mainly from the plains.";
std::string pattern = "nyoie";
removeLetters(s,pattern);
std::cout << s << std::endl;
return 0;
}

Run Here https://ideone.com/FmdSx

No comments :