0

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.

3
  • What is the problem? I don't see any obvious "garbage values"? It helps a lot if you describe both the output you're getting and the output you expected Commented Dec 2, 2013 at 12:12
  • Updated in the question Commented Dec 2, 2013 at 12:13
  • @DeveshAgrawal add str.erase(k); at the end of the RemoveChars function. Commented Dec 2, 2013 at 12:29

3 Answers 3

2

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; 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

I appreciate the answer. But it was asked to modify the original string. No extra space is allowed.
@DeveshAgrawal Then you might be interested in the resize method of std::string.
0

Use str.resize(k); instead of str[k] = '\0';

1 Comment

Its working fine with resize(k). my thought is it shouldn't be resize(k-1) ? because there is no char at kth place.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.