首页主机资讯c++中string怎么删除指定字符

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

时间2024-05-28 07:00:03发布访客分类主机资讯浏览597
导读:在C++中,可以使用erase方法来删除指定字符。下面是一个示例代码: #include <iostream> #include <string> int main( { std::string str...

在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方法来查找并删除指定的字符,直到找不到该字符为止。最后输出删除指定字符后的结果。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c++中string怎么删除指定字符
本文地址: https://pptw.com/jishu/669743.html
linux如何查看自己的ip地址 python如何删除代码中的某一行

游客 回复需填写必要信息