温馨提示×

c++ string如何删除指定字符

c++
小亿
82
2024-09-05 10:02:40
栏目: 编程语言

在 C++ 中,您可以使用 eraseremove 函数来删除 std::string 中的指定字符

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

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

    // 使用 remove 函数移除指定字符
    str.erase(std::remove(str.begin(), str.end(), charToRemove), str.end());

    std::cout << "String after removing '"<< charToRemove << "': "<< str<< std::endl;

    return 0;
}

在这个示例中,我们从字符串 “Hello, World!” 中删除了逗号。运行此代码将输出:

String after removing ',': Hello World!

请注意,std::remove 只是将不需要删除的字符移到字符串的前面,并返回一个迭代器,指向新的逻辑结尾。然后,erase 函数用于实际删除多余的字符。

0