温馨提示×

c++如何删除字符串中的某字符

c++
小亿
86
2024-09-03 10:43:32
栏目: 编程语言

在C++中,你可以使用std::string类的成员函数erase()来删除字符串中的某个字符。下面是一个示例代码:

#include<iostream>
#include<string>

int main() {
    std::string str = "Hello, World!";
    char ch = 'l'; // 要删除的字符

    for (size_t pos = str.find(ch); pos != std::string::npos; pos = str.find(ch)) {
        str.erase(pos, 1); // 删除找到的字符
    }

    std::cout << "删除字符 '" << ch << "' 后的字符串: "<< str<< std::endl;

    return 0;
}

这段代码首先定义了一个包含字符串"Hello, World!"的std::string对象str,然后使用find()函数查找要删除的字符(在这个例子中是字母’l’)。如果找到了该字符,find()函数将返回其在字符串中的位置,否则返回std::string::npos。接下来,我们使用erase()函数删除找到的字符,并继续查找直到找不到更多的该字符为止。最后,输出处理后的字符串。

0