开发者

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开发者_C百科 = "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?


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜