正在替换第一次出现的字符串,如何替换所有出现的字符串?

Am replacing the first occurrence of a string, how can I replace all occurrences?

我已经通过循环+替换构建了基本结构,在C++中,str.replace只是替换单个字符串,但是在某些情况下,我们需要替换所有相同的字符串,我的代码可以编译成功,可以输出到屏幕上,但是好像没有替换成功

提前致谢

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
int main(void)
{
    // initialize
    std::ofstream fout;
    std::ifstream fin;
    fout.open("cad.dat");
    fout <<  "C is a Computer Programming Language which is used worldwide, Everyone should learn how to use C" << std::endl;

    fin.open("cad.dat");
    std::string words;
    getline(fin,words);
    std::cout << words << std::endl;
 
    while(1)
    {
        std::string::size_type pos(0);
        if (pos = words.find("C") != std::string::npos && words[pos+1] != ' ') //the later one is used to detect the single word "C"
        {
            words.replace(pos, 1, "C++"); 
        }
        else
        {
            break;
        }
    }

    std::cout << words;
}

您需要保存 pos 并将其用于以下 find 操作,但您当前将其初始化为 0 while 循环中的每次迭代。

你可以用这个替换 while while 循环,例如:

for(std::string::size_type pos = 0;
    (pos = words.find("C", pos)) != std::string::npos; // start find at pos
    pos += 1)  // skip last found "C"
{
    if(pos + 1 == words.size() || words[pos + 1] == ' ')
        words.replace(pos, 1, "C++");
}

注意:这也将替换以 C 结尾的单词中的 C,例如像 C2C 这样的首字母缩略词将变为 C2C++。此外,不会处理以 C. 结尾的句子。要处理这些情况,您也可以在找到的 C 之前添加字符检查,并在检查中添加标点符号。

示例:

#include <cctype>   // isspace, ispunct
#include <iostream>
#include <string>

int main()
{
    std::string words = "C Computer C2C C. I like C, because it's C";
    std::cout << words << '\n';

    // a lambda to check for space or punctuation characters:
    auto checker = [](unsigned char ch) {
        return std::isspace(ch) || std::ispunct(ch);
    };

    for(std::string::size_type pos = 0;
        (pos = words.find("C", pos)) != std::string::npos;
        pos += 1)
    {
        if( (pos == 0 || checker(words[pos - 1])) &&
            (pos + 1 == words.size() || checker(words[pos + 1]))
        ) {
            words.replace(pos, 1, "C++");
        }
    }

    std::cout << words << '\n';
}

输出:

C Computer C2C C. I like C, because it's C
C++ Computer C2C C++. I like C++, because it's C++

您可以 简化 您的程序,只需使用 regex 如下:

std::regex f("\bC\b");
words = std::regex_replace(words, f, "C++"); // replace "C" with "C++"

那么不需要 while 循环,如下面的程序所示:


#include <iostream>
#include <fstream>
#include <regex>
#include <string>
int main(void)
{
    // initialize
    std::ofstream fout;
    std::ifstream fin;
    fout.open("cad.dat");
    fout <<  "C is a Computer Programming Language which is used worldwide, Everyone should learn how to use C" << std::endl;

    fin.open("cad.dat");
    std::string words;
    getline(fin,words);
    std::cout << words << std::endl;
 
    std::regex f("\bC\b");
    words = std::regex_replace(words, f, "C++"); // replace "C" with "C++"

    std::cout << words;
}