0

我刚刚写了一个基于 Qt 的php addSlashes函数,我不会看到任何改进和建议。我打算使用这个函数来填充一个包含数百个insert查询的文件,更具体地说,我将创建php 数据库转储之类的。

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]);

     }
    return newStr;
}
4

1 回答 1

0

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.

于 2011-05-11T01:58:56.803 回答