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

Time:11-05

This code only deletes 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?

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


}

CodePudding user response:

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 

CodePudding user response:

This could be done using regex:

#include <regex>

std::string str("Hello |start| world |end|");
std::regex removed_reg("\\|.*?\\|");

str = std::regex_replace(str, removed_reg, "");
std::cout << str;

Output: Hello world

  •  Tags:  
  • c
  • Related