📜  C++ 查找和替换子字符串

📅  最后修改于: 2020-08-28 06:52:47             🧑  作者: Mango

在本文中,我们将讨论如何在C++中用新字符串替换所有出现的子字符串。

例如,我们有一个字符串,即“Boost Library is simple C++ Library”

我们想用XXX替换所有出现的“ Lib”, 我们大概介绍3中常用的方法:

使用STL查找和替换所有子字符串

#include 
#include 
void findAndReplaceAll(std::string & data, std::string toSearch, std::string replaceStr)
{
    // Get the first occurrence
    size_t pos = data.find(toSearch);
    // Repeat till end is reached
    while( pos != std::string::npos)
    {
        // Replace this occurrence of Sub String
        data.replace(pos, toSearch.size(), replaceStr);
        // Get the next occurrence from the current position
        pos =data.find(toSearch, pos + replaceStr.size());
    }
}
int main()
{
    std::string data = "Boost Library is simple C++ Library";
    std::cout<

输出如下:

Boost Library is simple C++ Library
Boost XXXrary is simple C++ XXXrary

使用Boost :: replace_all查找和替换所有子字符串

#include 
#include 
#include 
int main()
{
    std::string data = "Boost Library is simple C++ Library";
    std::cout<

输出如下

Boost Library is simple C++ Library
Boost XXXrary is simple C++ XXXrary

使用Boost :: ireplace_all查找并替换所有不区分大小写的子字符串

#include 
#include 
#include 
int main()
{
    std::string data = "Boost Library is simple C++ Library";
    std::cout<

在第三种方法中,不区分子字符串的大小写,输出与前两种一致。

 

——————–》》》