C + + implementation UrlEncode and UrlDecode

Source: Internet
Author: User
Tags reserved urlencode

#include "stdafx.h"

#include

#include

#include

using namespace Std;

std::string urlencode (const std::string& Sztoencode)

{

std::string src = sztoencode;

Char hex[] = "0123456789ABCDEF";

string DST;

for (size_t i = 0; i < src.size (); ++i)

{

unsigned char cc = src[i];

if (Isascii (cc))

{

if (cc = = ")

{

DST + + "%20";

}

Else

DST + + cc;

}

Else

{

unsigned char c = static_cast (Src[i]);

DST + = '% ';

DST + + HEX[C/16];

DST + + hex[c% 16];

}

}

return DST;

}

std::string urldecode (const std::string& Sztodecode)

{

std::string result;

int hex = 0;

for (size_t i = 0; i < sztodecode.length (); ++i)

{

Switch (Sztodecode[i])

{

Case ' + ':

result = = ';

Break

Case '% ':

if (Isxdigit (Sztodecode[i + 1]) && isxdigit (Sztodecode[i + 2])

{

std::string hexstr = sztodecode.substr (i + 1, 2);

Hex = Strtol (hexstr.c_str (), 0, 16);

Letters and numbers [0-9a-za-z], some special symbols [$-_.+!* ' (),], and some reserved words [$&+,/:;=?@]

can be used without encoding directly for URLs

if (!) ( (Hex >= && hex <= 57) | | 0-9

(Hex >=97 && hex <= 122) | | A-Z

(Hex >=65 && hex <= 90) | | A-Z

Some special symbols and reserved words [$-_.+!* ' (),] [$&+,/:;=?@]

Hex = = 0x21 | | Hex = = 0x24 | | Hex = = 0x26 | | Hex = = 0X27 | | Hex = = 0x28 | | Hex = = 0x29

|| Hex = = 0X2A | | Hex = = 0x2b| | Hex = = 0X2C | | Hex = = 0x2d | | Hex = = 0x2e | | Hex = = 0x2f

|| Hex = = 0X3A | | Hex = = 0x3b| | Hex = = 0x3d | | Hex = = 0x3f | | Hex = = 0x40 | | Hex = = 0x5f

))

{

Result + = char (hex);

i + 2;

}

else result = '% ';

}else {

result = '% ';

}

Break

Default

result = Sztodecode[i];

Break

}

}

return result;

}

/*

int main ()

{

String test_str1 = "Shuangshuang";

String test_str2 = UrlEncode (TEST_STR1);

cout << test_str2 << Endl;

}

*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.