c++ – why cant i replace char on a string like this?

c++ – why cant i replace char on a string like this?

Following code works for me:

#include <string>
#include <map>
#include <regex>
#include <iostream>

using namespace std;

int main() {
    const map<char, vector<char>> ass = {
        { 1, {i} },
        { 0, {o} },
    };

    string char1;
    string char2;
    string wr = c1a0;

    for (auto const &ent1 : ass) {

        for (int i = 0; i < ent1.second.size(); i++) {

            //specialValues += ent1.second[i];

            char2 = ent1.second[i];
            char1 = ent1.first;

            regex e(([ + char1 + ]));

            cout << (([ + char1 + ])) << std::endl;
            cout << char2<< std::endl;

            wr = regex_replace(wr, e, char2);
            cout << wr << std::endl;

        }

    }
}

But IMHO, regex here is overkill. You can iterate over string manually and replace character like in the following snippet:

#include <string>
#include <set>
#include <iostream>
#include <vector>

using namespace std;

struct replace_entry {
    char with;
    std::set<char> what;
};

int main() {
    const std::vector<replace_entry> replaceTable = {
        { i, {1} },
        { o, {0} },

    };

    string input = c1a0;

    for (auto const &replaceItem : replaceTable) {
        for (char& c: input ) {
            if(replaceItem.what.end() != replaceItem.what.find(c)) {
                c = replaceItem.with;
            }
        }

    }
    cout << input << std::endl;
}

Yet another approach is to create 256 elements array of chars

#include <string>
#include <iostream>

class ReplaceTable {
private:
    char replaceTable_[256];

public:
    constexpr ReplaceTable() noexcept 
        : replaceTable_()
    {
        replaceTable_[0] = o;
        replaceTable_[1] = i;
    }

    constexpr char operator[](char what) const noexcept {
        return replaceTable_[what];
    }

};

// One time initialization
ReplaceTable g_ReplaceTable;

int main() {

    std::string input = c1a0;

    // Main loop
    for (char& c: input ) {
        if(0 != g_ReplaceTable[c] ) c = g_ReplaceTable[c];
    }

    std::cout << input << std::endl;
}

c++ – why cant i replace char on a string like this?

Leave a Reply

Your email address will not be published. Required fields are marked *