Home > Net >  The erase function of strings in c
The erase function of strings in c

Time:10-18

well I was doing this problem from leetcode " https://leetcode.com/problems/valid-palindrome/ " and to remove the punctuations I used this

for (auto i:s)
{
    if (ispunct(i))
    {
        s.erase(remove(s.begin(), s.end(), i), s.end());
        continue;
    }    
}

but when it runs it leaves some punctuation characters in the string like this: ip-> "Marge, let's "[went]." I await {news} telegram." op-> "margelets[wentiawaitnewstelegram"

CodePudding user response:

Modifying a string (or any other collection) while looping over it is a poor idea. Your iterator into the string is based on the state of the string at the beginning of your loop. Changing the state of the string inside the loop may lead to unexpected behavior of your iterator.

Rather you may want to create a new string without the offending characters.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
  std::string s1 = "Hello world!";
  std::string s2;

  std::copy_if(s1.begin(), s1.end(), 
               std::back_inserter(s2), 
               [](auto ch) { return !std::ispunct(ch); });

  std::cout << s2 << std::endl;

  return 0;
}
  •  Tags:  
  • c
  • Related