温馨提示×

c++中string怎么删除指定字符

c++
小亿
512
2024-04-12 11:35:02
栏目: 编程语言

在C++中,可以使用erase方法来删除指定字符。下面是一个示例代码:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello World!";
    char charToRemove = 'o';

    size_t pos = 0;
    while ((pos = str.find(charToRemove, pos)) != std::string::npos) {
        str.erase(pos, 1);
    }

    std::cout << "After removing '" << charToRemove << "': " << str << std::endl;

    return 0;
}

在上面的代码中,我们首先定义了一个字符串str和要删除的字符charToRemove。然后使用find方法来查找并删除指定的字符,直到找不到该字符为止。最后输出删除指定字符后的结果。

0