I think I'd separate the data from the code, something like:
std::map<char, std::string> reps;
reps['\0'] = "\\\0";
reps['\''] = "\\'";
reps['\"'] = "\\\"";
reps['\\'] = "\\\\";
for (int i=0; i<str.length(); i++)
if ((pos=reps.find(str[i])!=reps.end())
newStr.append(pos->second);
else
newStr.append(str[i]);
You may, of, course prefer to use a QMap
instead of a std::map
though. That'll change how you spell a few things, but doesn't change the basic idea.
Alternatively, since each "special" output is just the original character preceded by a backslash, you could just use an std::set
of characters that need a backslash:
std::set<char> needs_slash;
needs_slash.insert('\'');
needs_slash.insert('\"');
needs_slash.insert('\0');
needs_slash.insert('\\');
for (int i=0; i<str.length(); i++) {
if (needs_slash.find(str[i]) != needs_slash.end())
newStr.append('\\');
newStr.append(str[i]);
}
Given the small number of characters involved, you could also use something like an std::bitset
or std::vector<bool>
as well. We're talking about 32 bytes of storage (assuming you only care about 256 characters). When you get down to it, the map/set is just being used as a sparse array, but if you're only using it in one (or even a few) places, you'll undoubtedly save more space (in code) by using an array than you save (in data) by using the set/map.