我知道这个问题经常出现,但我找不到一段适合我的代码。
我正在尝试使用字符串库中的 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 传递到哪里?
最佳答案
永远不要通过 .end()。它指向一个无效的迭代器,它代表结束。 如果要删除字符串中的最后一个字符,请使用 temp.erase(temp.length()-1)。 如果我理解正确的话。
编辑:
it seems erase() only accepts an iterator, which is what i thought initially.
这不是真的:
string& erase ( size_t pos = 0, size_t n = npos );
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );
关于c++ - 使用 string::find_first_not_of 和 string::find_last_not_of 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755652/