C ++ implements UrlEncode and UrlDecode

Source: Internet
Author: User

# Include "stdafx. h"

# Include

# Include

# Include

Using namespace std;

Std: string UrlEncode (const std: string & szToEncode)

{

Std: string src = szToEncode;

Char hex [] = "0123456789 ABCDEF ";

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 [$ & +,/:; =? @]

// URL can be used directly without Encoding

If (! (Hex> = 48 & 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 = "refreshing ";

String test_str2 = UrlEncode (test_str1 );

Cout <test_str2 <endl;

}

*/

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.