c语言进行urlencode编码,c语言urlEncode实现

#include "stdafx.h"

#include "assert.h"

#include

using namespace std;

unsigned char ToHex(unsigned char x)

{

return x > 9 ? x + 55 : x + 48;

}

unsigned char FromHex(unsigned char x)

{

unsigned char y;

if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;

else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;

else if (x >= '0' && x <= '9') y = x - '0';

else assert(0);

return y;

}

std::string UrlEncode(const std::string& str)

{

std::string strTemp = "";

size_t length = str.length();

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

{

if (isalnum((unsigned char)str[i]) ||

(str[i] == '-') ||

(str[i] == '_') ||

(str[i] == '.') ||

(str[i] == '~'))

strTemp += str[i];

else if (str[i] == ' ')

strTemp += "+";

else

{

strTemp += '%';

strTemp += ToHex((unsigned char)str[i] >> 4);

strTemp += ToHex((unsigned char)str[i] % 16);

}

}

return strTemp;

}

std::string UrlDecode(const std::string& str)

{

std::string strTemp = "";

size_t length = str.length();

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

{

if (str[i] == '+') strTemp += ' ';

else if (str[i] == '%')

{

assert(i + 2 < length);

unsigned char high = FromHex((unsigned char)str[++i]);

unsigned char low = FromHex((unsigned char)str[++i]);

strTemp += high * 16 + low;

}

else strTemp += str[i];

}

return strTemp;

}

int main()

{

string oriString = "我是一个 兵00134@#$*%/.a^%$#*&$#@~!@+=2";

string resultString = UrlEncode(oriString);

string decodeString = UrlDecode(resultString);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值