Reputation: 9212
To remove set of chars from a given string, i have implemented this function.
void removeChars (string& str, const string& chars)
{
vector <bool> v (256, false);
for (int i=0; i < chars.size(); ++i)
{
v[chars[i]] = true;
}
int k=0;
for (int j=0; j < str.size(); ++j)
{
if (v[str[j]]==false)
{
str[k] = str[j];
++k;
}
}
str[k] = '\0';
}
But after processing the string from this function. Its printing some garbage value.
string s1 = "trying to remove chars from string";
string s2 = "tr";
removeChars2 (s1, s2);
Now print s1
ying o emove chas fom sing string
Expected : ying o emove chas fom sing
is there anything wrong in this implementation.
Upvotes: 0
Views: 109
Reputation: 409442
You should not add terminator character for std::string
, it keeps track of the string end in other ways.
Instead of modifying str
directly, I would recommend you append characters to a new string, and then copy that string to str
when done.
Upvotes: 1
Reputation: 3299
Use STL algorithms, and you don't have to reimplement everything :)
string text("trying to remove chars from string");
char toRemove[] = "tr";
for (unsigned int i = 0; i < strlen(toRemove); ++i)
text.erase(std::remove(text.begin(), text.end(), toRemove[i]), text.end());
std::cout << text << std::endl;
Upvotes: 2