Rivasa
Rivasa

Reputation: 6750

How to replace multiple sets of keywords in a string?

So I have a file of strings that I am reading in, and I have to replace certain values in them with other values. The amount of possible replacements is variable. As in, it reads the patterns to replace with in from a file. Currently I'm storing in a vector<pair<string,string>> for the patterns to find and match. However I run into issues:

Example:

Input string: abcd.eaef%afas&333

Delimiter patterns:

. %%%

% ###

& @@@

Output I want: abcd%%%eaef###afas@@@333

Output I get: abcd#########eaef###afas@@@333

The issue being it ends up replacing the % sign or any other symbol that was already a replacement for something else, it should not be doing that.

My code is (relevant portions):

std::string& replace(std::string& s, const std::string& from, const std::string& to){
    if(!from.empty())
        for(size_t pos = 0; (pos = s.find(from, pos)) != std::string::npos; pos += to.size()) s.replace(pos, from.size(), to);
    return s;
}
string line;
vector<pair<string, string>> myset;
while(getline(delimiterfile, line)){
    istringstream is(line);
    string delim, pattern;
    if(is >> delim >> pattern){
        myset.push_back(make_pair(delim, pattern));
    } else {
        throw runtime_error("Invalid pattern pair!");
    }
}

while(getline(input, line)){
    string temp = line;
    for(auto &item : myset){
        replace(temp, item.first, item.second);
    }
    output << temp << endl;
}

Can someone please tell me what I'm messing up and how to fix it?

Upvotes: 0

Views: 685

Answers (2)

kirilov
kirilov

Reputation: 26

I would suggest you use stringstream. This way you will be able to achieve what you are looking for very easily.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409266

In pseudo-code a simple replacement algorithm could look something like this:

string input = getline();
string output;  // The string containing the replacements
for (each char in input)
{
    if (char == '.')
        output += "%%%";
    // TODO: Other replacements
    else
        output += char;
}

If you implement the above code, once it's done the variable output will contain the string with all replacements made.

Upvotes: 2

Related Questions