dtg
dtg

Reputation: 1853

Problems using string::find_first_not_of and string::find_last_not_of

I know this problem crops up a lot, but I couldn't find a piece of code which worked for me.

I am trying to strip all punctuation off of an incoming string using find_first_not_of and find_last_not_of methods in the string library:

//
//strip punctuation characters from string
//
void stripPunctuation(string &temp)
{
    string alpha = "abcdefghijklmnopqrstuvwxyz";

    size_t bFound = temp.find_first_not_of(alpha); 
    size_t eFound = temp.find_last_not_of(alpha);

    if(bFound != string::npos)
        temp.erase(temp.begin());
    if(eFound != string::npos)
        temp.erase(temp.end());
}

Basically, I want to delete anything at the front of the string that is not alphabetic and anything at the end of the string which is not alphabetic. When this function gets called, it results in a segmentation fault. I am not sure where I should be passing bFound and eFound?

Upvotes: 1

Views: 1904

Answers (1)

user852830
user852830

Reputation:

Never pass .end(). It points to an invalid iterator, which represents the end. If you want to delete the last character in a string, use temp.erase(temp.length()-1). If I understand you correctly.

edit:

it seems erase() only accepts an iterator, which is what i thought initially.

That is not true:

string& erase ( size_t pos = 0, size_t n = npos );
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );

http://www.cplusplus.com/reference/string/string/erase/

Upvotes: 1

Related Questions