954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Removing punctuation from string issue

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

randrum1707
Newbie Poster
11 posts since Feb 2012
Reputation Points: 10
Solved Threads: 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.

randrum1707
Newbie Poster
11 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

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

if(ispunct(string1[i]))
 {
       string1.erase(i,1);
       i--;
 }
mazzica1
Junior Poster
147 posts since Oct 2011
Reputation Points: 9
Solved Threads: 27
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: