工作需要urlencode,网上很多代码并不行,直至 用到
有空再添加decode
http://blog.youkuaiyun.com/zaccheodong/article/details/6951868
,
再添加一个格式函数string UrlUTF8( string tt),就可以了,如下
#include "stdafx.h"
#include <iostream>#include <windows.h>
#include <string>
//#include <tchar.h >
#include <assert.h>
using namespace std;
std::wstring ANSI_2_UTF16( const string& strANSI )
{
int nUnicodeLength = ::MultiByteToWideChar(CP_ACP,0,strANSI.c_str(),-1,NULL,0) ;
wstring strUTF16(nUnicodeLength,_T(' '));
int nRet = ::MultiByteToWideChar(CP_ACP,0,strANSI.c_str(),-1,&strUTF16[0],nUnicodeLength);
assert(0 != nRet);
return strUTF16;
}
// UNIcode默认的UTF16编码转为 ansi 在本机是MBCS(实际上是DBCX)
std::string UTF16_2_ANSI( const wstring& strUTF16 )
{
int nANSILength = ::WideCharToMultiByte(CP_ACP,0,strUTF16.c_str(),-1,NULL,0,0,0);
string strANSI(nANSILength,' ');
int nRet = ::WideCharToMultiByte(CP_ACP,0,strUTF16.c_str(),-1,&strANSI[0],nANSILength,0,0);
assert(0 != nRet);
return strANSI;
}
// UNIcode默认的UTF16编码转为 UTF8编码
std::string UTF16_2_UTF8( const wstring& strUTF16 )
{
int nUTF8Length = ::WideCharToMultiByte(CP_UTF8,
0,
strUTF16.c_str(),
-1,
NULL,
0,
0,0);
string strUTF8(nUTF8Length+1,'\0');
int nRet = ::WideCharToMultiByte(CP_UTF8,
0,
strUTF16.c_str(),
-1,
&strUTF8[0],
nUTF8Length+1,
0,
0);
return strUTF8;
}
// UNIcode UTF8编码 转为 UNIcode默认的UTF16编码
std::wstring UTF8_2_UTF16( const string& strUTF8 )
{
int nUTF16Length = ::MultiByteToWideChar(CP_UTF8,0,strUTF8.c_str(),-1,NULL,0);
nUTF16Length += 1;
wstring strUTF16(nUTF16Length ,' ');
int nRet = ::MultiByteToWideChar(CP_UTF8,0,strUTF8.c_str(),-1,
&strUTF16[0],nUTF16Length);
assert(0 != nRet);
return strUTF16;
}
//UTF8 编码的UNICODE字符集转为ANSI编码,先转换为UTF16编码,再转换为ANSI编码
std::string UTF8_2_ANSI( const string& strUTF8 )
{
wstring wstrUTF16 = UTF8_2_UTF16(strUTF8);
string strANSI = UTF16_2_ANSI(wstrUTF16);
return strANSI;
}
//ANSI编码 转为 UTF8编码的,先转换为UTF16编码,再转换为UTF8编码
std::string ANSI_2_UTF8( const string& strANSI )
{
wstring wstrUTF16 = ANSI_2_UTF16(strANSI);
string strUTF8 = UTF16_2_UTF8(wstrUTF16);
return strUTF8;
}
string UrlUTF8( string tt)
{
// string tt;
string dd;
//GB2312ToUTF_8(tt,str,(int)strlen(str));
//size_t len=tt.length();// 这个是原来的编码
size_t len=tt.length()-2; //至今还没有弄明白为什么-2, 但如果没有-2 后面多 %00%00
for (size_t i=0;i<len;i++)
{
if(isalnum((BYTE)tt.at(i)))
{
char tempbuff[2]={0};
sprintf(tempbuff,"%c",(BYTE)tt.at(i));
dd.append(tempbuff);
}
else if (isspace((BYTE)tt.at(i)))
{
// dd.append("+");
dd.append("%20");
// %20
}
else
{
char tempbuff[4];
sprintf(tempbuff,"%%%X%X",((BYTE)tt.at(i)) >>4,((BYTE)tt.at(i)) %16);
dd.append(tempbuff);
}
}
return dd;
}
int main()
{
string test_str1 = "东莞 有限公司";
string test_str2 = ANSI_2_UTF8(test_str1);
string test_str3=UrlUTF8( test_str2);
cout << test_str3 << endl;
}