c++ - Qt based addSlashes version equivalent -


i wrote qt based php addslashes function like, wont see improvements, suggestions it. planing use function fill file hundred of insert query, more specific, going 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]);       }     return newstr; } 

i think i'd separate data code, like:

std::map<char, std::string> reps;  reps['\0'] = "\\\0"; reps['\''] = "\\'"; reps['\"'] = "\\\""; reps['\\'] = "\\\\";  (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 use qmap instead of std::map though. that'll change how spell few things, doesn't change basic idea.

alternatively, since each "special" output original character preceded backslash, use std::set of characters need backslash:

std::set<char> needs_slash;  needs_slash.insert('\''); needs_slash.insert('\"'); needs_slash.insert('\0'); needs_slash.insert('\\');  (int i=0; i<str.length(); i++) {     if (needs_slash.find(str[i]) != needs_slash.end())         newstr.append('\\');     newstr.append(str[i]); } 

given small number of characters involved, use std::bitset or std::vector<bool> well. we're talking 32 bytes of storage (assuming care 256 characters). when down it, map/set being used sparse array, if you're using in 1 (or few) places, you'll undoubtedly save more space (in code) using array save (in data) using set/map.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -