c++ - 使用 string::find_first_not_of 和 string::find_last_not_of 的问题

标签 c++ string stl erase

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

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

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

关于c++ - 使用 string::find_first_not_of 和 string::find_last_not_of 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755652/

相关文章:

c++ - 如何制作更安全的 C++ 变体访问者,类似于 switch 语句?

c++ - 需要有关反转输入的递归程序的帮助

c++ - streambuf 获取 streampos

c++ - STL std::map 的 MFC 等价物

c++ - 这里使用迭代器有什么问题

c++ - PCRE中的匹配顺序

c++ - *函数签名*(作为反对类型)的*唯一*目的是在潜在的重载集中定义重复项——还是有其他目的?

c - C 相等运算符是否比较两个字符串的字面值或其内存位置?

java - 字符串替换用 $ 符号抛出错误

c++ - 如何在 C++ while 循环中创建一个自动递增数组?