使用string::find_first_not_of和string::find_last_not_of的问题

Problems using string::find_first_not_of and string::find_last_not_of

本文关键字:not string find of last 问题 first 使用      更新时间:2023-10-16

我知道这个问题经常出现,但是我找不到一段适合我的代码。

我试图在字符串库中使用find_first_not_of和find_last_not_of方法去除输入字符串的所有标点符号:

//
//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());
}

基本上,我想要删除字符串前面非字母的任何内容以及字符串末尾非字母的任何内容。当调用这个函数时,它会导致分段错误。我不确定我应该在哪里经过found and found ?

永远不要传递.end()。它指向一个无效的迭代器,它代表end。如果要删除字符串中的最后一个字符,请使用temp.erase(temp.length()-1)。如果我没理解错的话。

编辑:

似乎erase()只接受迭代器,这是我最初的想法。

这不是真的:

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/