php函数UrlEncode的C++版

CString s2utfs(const wstring& strSrc)
{
string strRes;
wstring wstrUni = strSrc;
char* chUTF8 = new char[wstrUni.length() * 3];
memset(chUTF8,0x00,wstrUni.length() * 3);
CString strName = Uni2UTF(wstrUni,chUTF8, wstrUni.length() * 3);
strRes = chUTF8; 
delete []chUTF8;
return strName;
}

CString URLEncode( const wstring& strRes, char *utf8, int nMaxSize )
{
if (utf8 == NULL) {
return L"";
}
CString strName;
int len = 0;
int size_d = nMaxSize;


for (wstring::const_iterator it = strRes.begin(); it != strRes.end(); ++it)
{
wchar_t wchar = *it;
if (wchar < 0x80)
{
strName += wchar;

continue;
}
else if(wchar < 0x800)
{
if (len + 1 >= size_d)
return L"";

utf8[len++] = 0xc0 | ( wchar >> 6 );
utf8[len++] = 0x80 | ( wchar & 0x3f );
}
else if(wchar < 0x10000 )
{
if (len + 2 >= size_d)
return L"";

utf8[len++] = 0xe0 | ( wchar >> 12 );
utf8[len++] = 0x80 | ( (wchar >> 6) & 0x3f );
utf8[len++] = 0x80 | ( wchar & 0x3f );
}
else if( wchar < 0x200000 ) 
{
if (len + 3 >= size_d)
return L"";

utf8[len++] = 0xf0 | ( (int)wchar >> 18 );
utf8[len++] = 0x80 | ( (wchar >> 12) & 0x3f );
utf8[len++] = 0x80 | ( (wchar >> 6) & 0x3f );
utf8[len++] = 0x80 | ( wchar & 0x3f );
}

char *q = new char[40];
char *p = utf8;
for (int i = 0;i < 3;i++)
{
char *q = new char[40];
sprintf(q,"%x",*p++);

strName += "%";

strName += q;
}

len = 0;
}
strName.Replace(L"ffffff",L"");

return strName;
}

 

posted @ 2013-07-10 16:59  旗木小西西  阅读(288)  评论(0)    收藏  举报