I would like to remove the punctuation at the start of a string and at the end.
My code so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string remPunc(string &word)
{
for(int i = 0; i < word.length(); i++){
if(ispunct(word[i])){
word.erase(i, 1);
}
}
return word;
}
int main(){
string word("&&&Hello&&&");
remPunc(word);
cout << word << endl;
}
This currently outputs:
&Hello&
I don't understand why the loop doesn't erase the punctuation just before and after the string. Also if I change the string to just "&Hello&", the punctuation is removed. Would appreciate some help as to what's happening here, thanks!
You erase an element, but your index i doesn't take this into account. You need to update your index as well after erasing an element, since everything gets shifted to the left.
The first iteration through, you remove the first character, leaving the string "&&hello&&&". The next iteration you are looking for index 1 (which is now the second '&'. It gets removed, and you have "&hello&&&". Now you are looking at index 2 which is the 'e'.
If you want to only remove punctuation from start and end of string look at std::string::find_first_not_of()[1] and std::string::find_last_not_of()[2] to use with std::string::erase().