Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete those string from file which is followed by "|" and end with "|"?

int main()
{
std::ifstream in_file("Test-1.txt");
    std::ofstream out_file("output.txt");

    std::string str;
    const std::string removed_str = "|start|";

    while (std::getline(in_file, str)) {
        std::size_t ind = str.find(removed_str);
        std::cout << str << std::endl;
        if (ind != std::string::npos)
        {
            str.erase(ind, removed_str.length());
        }

        std::cout << str << std::endl;

        out_file << str << std::endl;
    }


}

/* This code only delete a string which I provide it in removed_str variable but I want to delete all the string which start from "|" and ends with "|". How should i do it. Kindly help me fix it. /*

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you please try this one ?

#include <iostream>
#include <fstream>
#include <regex>

int main ()
{
    const std::regex pattern("\\|(.*?)\\|");
    std::ifstream in_file("input.txt");
    std::ofstream out_file("output.txt"); 

    std::string str;

    while (std::getline(in_file, str)) {
        str = std::regex_replace(str, pattern, "");
        std::cout << str << std::endl;

        out_file << str << std::endl;
    }

    return 0;
}

input.txt

Line1 |start| |start|
Line2   |start| |start|
Line3 Line1 Line2 |start|

output.txt

Line1  
Line2    
Line3 Line1 Line2 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading