1

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

我正在尝试使用字符串库中的 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());
}

基本上,我想删除字符串前面不是字母的任何内容以及字符串末尾不是字母的任何内容。调用此函数时,会导致分段错误。我不确定我应该在哪里传递 bFound 和 eFound?

4

1 回答 1

1

永远不要通过 .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/

于 2011-07-20T00:31:22.390 回答