首页 > 解决方案 > 有没有办法可以从字符串中删除一个字符?

问题描述

我想从 a 中删除一个字符('#')string

我试图检查函数是否string有'#' find,它确实如此,然后用erase函数擦除它。

出于某种原因,我收到一个运行时错误,说我没有记忆。

错误:std::out_of_range at memory location 0x003BF3B4

#include <iostream>
#include <algorithm>
#include <string>

int main()
{
    std::string str = "Hello World#";

    if (str.find('#')) {
        str.erase('#');
    }

    return 0;
}

例外的输出是:“Hello World”

标签: c++windows

解决方案


尝试这样的事情:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), '#'), str.end());

推荐阅读