-1

This is a piece of code that I found online, basically, it helps me to erase all the punctuation in a string.

for(size_t i = 0; i<text.length(); ++i)   
if(ispunct(text[i]))     
text.erase(i--, 1);

Like in the sentence: "hello, I am John". It will delete the comma. But I do not understand why in the code:

text.erase(i--, 1);

I do not understand why it delete the text[i--](which is o in this case), but when the code run, it works perfectly and does not erase "o". I know that I misunderstand that part. Can somebody explain to me about that?

  • 2
    read about the difference between post- and pre- in/decrement – 463035818_is_not_an_ai Oct 17 '22 at 09:33
  • The `--` after a variable is a postdecrement. It subtracts 1 *after* using the value. When you delete the punctuation, it should continue with the same index. As the for loop increases `i`, this increase is countered by doing a decrement first. The shown code is inefficient as it calculates the length with each iteration in the condition of the for loop. Also be careful about character representations (e.g. codepages, variable width characters). Please improve the indentation of the code in your question. – Sebastian Oct 17 '22 at 09:34

1 Answers1

1

++i pre- in/decrement will increment i before using it,
so if i is 1 it will first update it to 2 and than use it.

i-- pos- in/decrement will use i before decrementing it,
so if i is 5 it will use 5 and than update it to 4

Connor Stoop
  • 1,574
  • 1
  • 12
  • 26