Qt based addSlashes version equivalent
I just wrote a Qt based php addSlashes function like, I wont to see any improvements, suggestions to it. I am planing to use this function to fill a file with hundred of insert
query, to be more specific, I am going to create php database dump like.
QString addSlashes(QString str)
{
QString newStr;
for(int i=0;i<str.length();i++)
{
if(str[i] == '\0')
{
newStr.append('\\');
newStr.append('0');
}
else if(str[i] == '\'')
{
newStr.append('\'');
}
else if(str[i] == '\"')
{
newStr.append('\"');
}
else if(str[i] == '\\')
{
newStr.append('\\');
}
else
newStr.append(str[i]);开发者_JAVA技巧
}
return newStr;
}
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.
精彩评论