📜  c++ 字符串擦除所有出现 - C++ (1)

📅  最后修改于: 2023-12-03 15:13:59.983000             🧑  作者: Mango

C++字符串擦除所有出现

在C++中,有多种方法可以擦除字符串中所有出现的特定字符。在本文中,我们将介绍其中的一些方法。

方法一:使用std::replace

我们可以使用std::replace函数来替换字符串中所有出现的指定字符。以下是该函数的语法:

std::replace(str.begin(), str.end(), char_to_replace, replacement_char);

其中,str是要修改的字符串,char_to_replace是要替换的字符,replacement_char是替换后的字符。

以下是一个例子:

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

int main()
{
    std::string str = "this is a string";
    std::replace(str.begin(), str.end(), 'i', ' ');

    std::cout << str << std::endl;
    // 输出:th s   s a str ng
    return 0;
}
方法二:使用std::remove和std::string的erase

我们可以使用std::remove函数来将指定字符移到字符串末尾,并返回一个指向第一个移动元素的迭代器。然后,我们可以使用std::string的erase函数删除该迭代器之后的所有字符。以下是该方法的示例代码:

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

int main()
{
    std::string str = "this is a string";
    str.erase(std::remove(str.begin(), str.end(), 'i'), str.end());

    std::cout << str << std::endl;  
    // 输出:ths  a strng
    return 0;
}
方法三:使用std::string的find和erase

我们可以使用std::string的find函数来找到字符串中第一个出现指定字符的位置,并使用erase函数删除该字符。然后,我们可以在循环中重复这个过程,直到没有找到该字符。以下是该方法的示例代码:

#include <string>
#include <iostream>

int main()
{
    std::string str = "this is a string";
    char char_to_erase = 'i';

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

    std::cout << str << std::endl; 
    // 输出:ths  a strng
    return 0;
}
总结

这篇文章介绍了使用C++中的多个函数和方法来擦除字符串中所有出现的特定字符。不同的方法适用于不同的场景和需求,选择合适的方法可以提高代码的效率和可读性。