Home > OS >  Replace the all same string C
Replace the all same string C

Time:11-07

I have already bulid the basic structure by using the loop replace,In C , the str.replace is only to replace single string, however, in some cases, we need to replace all the same string, My code can compile successfully and can output to the screen, but it seems that it does not replace successfully. here's my code:

#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;
}

CodePudding user response:

You need to save pos and use it for the following find operations but you currently initialize it to 0 every iteration in the while loop.

You could replace the while while loop with this for example:

for(std::string::size_type pos = 0;
    (pos = words.find("C", pos)) != std::string::npos; // start find at pos
    pos  = 3)  // skip "C  "
{
    words.replace(pos, 1, "C  ");
}

CodePudding user response:

You can simplify your program by just using regex as follows:

words = std::regex_replace(words, std::regex("C"), "C  "); // replace "C" with "C  "

Then there is no need for a while loop as shown in the below program:

#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;
 
    
    words = std::regex_replace(words, std::regex("C"), "C  "); // replace "C" with "C  "

    std::cout << words;
}
  • Related