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


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

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

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

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

#include <iostream>
#include <string>
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<<data<<std::endl;
    findAndReplaceAll(data, "Lib", "XXX");
    std::cout<<data<<std::endl;
    return 0;
}

输出如下:

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

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

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
    std::string data = "Boost Library is simple C++ Library";
    std::cout<<data<<std::endl;
    // Replace all occurrences of 'LIB' with 'XXX'
    // Case Sensitive Version
    boost::replace_all(data, "Lib", "XXX");
    std::cout<<data<<std::endl;
}

输出如下

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

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

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
    std::string data = "Boost Library is simple C++ Library";
    std::cout<<data<<std::endl;
    // Replace all occurrences of 'LIB' with 'XXX'
    // Case Insensitive Version
    boost::ireplace_all(data, "LIB", "XXX");
    std::cout<<data<<std::endl;
}

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

 

——————–》》》

0



error: 内容受到保护 !!