0

Hey everyone,

I'm trying to remove all punctuation from a string of characters. Here is the part of the code that I'm using to remove the punctuation from the string (string1 being the string).

for (int i =0; string1[i]; i++)
             {
             if(ispunct(string1[i]))
             string1.erase(i,1);
             }

It is removing punctuation perfectly fine and leaving behind no whitespace (which is what I want) except for when there are two punctuation marks next to each other. Here is an example of what I mean.

Input string: "This is a sample of input," said I, "and some punctuation remains."
Output: This is a sample of input" said I and some punctuation remains"

It seems when there are two or more punctuation marks next to each other, the one on the farthest right is left in the string. Anyone have any idea why this is? Thanks

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by mazzica1
0

Nevermind, I figured it out! When I delete the punctuation mark it moves the next character in the string to the current position and then i++ increased it to the next one (thereby skipping punctuation). I fixed it by changing the if statement to while.

0

cause when you erase the size changes and i looks at new pos

if(ispunct(string1[i]))
 {
       string1.erase(i,1);
       i--;
 }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.