首页 > 代码库 > c++ encode decode

c++ encode decode

 1 std::string UrlEncode(const std::string& szToEncode) 2 { 3     std::string src =http://www.mamicode.com/ szToEncode; 4     char hex[] = "0123456789ABCDEF"; 5     string dst; 6   7     for (size_t i = 0; i < src.size(); ++i) 8     { 9         unsigned char cc = src[i];10         if (isascii(cc))11         {12             if (cc ==  )13             {14                 dst += "%20";15             }16             else17                 dst += cc;18         }19         else20         {21             unsigned char c = static_cast<unsigned char>(src[i]);22             dst += %;23             dst += hex[c / 16];24             dst += hex[c % 16];25         }26     }27     return dst;28 }29  30  31 std::string UrlDecode(const std::string& szToDecode)32 {33     std::string result;34     int hex = 0;35     for (size_t i = 0; i < szToDecode.length(); ++i)36     {37         switch (szToDecode[i])38         {39         case +:40             result +=  ;41             break;42         case %:43             if (isxdigit(szToDecode[i + 1]) && isxdigit(szToDecode[i + 2]))44             {45                 std::string hexStr = szToDecode.substr(i + 1, 2);46                 hex = strtol(hexStr.c_str(), 0, 16);47                 //字母和数字[0-9a-zA-Z]、一些特殊符号[$-_.+!*‘(),] 、以及某些保留字[$&+,/:;=?@]48                 //可以不经过编码直接用于URL49                 if (!((hex >= 48 && hex <= 57) || //0-950                     (hex >=97 && hex <= 122) ||   //a-z51                     (hex >=65 && hex <= 90) ||    //A-Z52                     //一些特殊符号及保留字[$-_.+!*‘(),]  [$&+,/:;=?@]53                     hex == 0x21 || hex == 0x24 || hex == 0x26 || hex == 0x27 || hex == 0x28 || hex == 0x2954                     || hex == 0x2a || hex == 0x2b|| hex == 0x2c || hex == 0x2d || hex == 0x2e || hex == 0x2f55                     || hex == 0x3A || hex == 0x3B|| hex == 0x3D || hex == 0x3f || hex == 0x40 || hex == 0x5f56                     ))57                 {58                     result += char(hex);59                     i += 2;60                 }61                 else result += %;62             }else {63                 result += %;64             }65             break;66         default:67             result += szToDecode[i];68             break;69         }70     }71     return result;72 }

在线测试工具:http://tool.chinaz.com/Tools/URLEncode.aspx