Unicode下汉字URLEncode解决方法

来源:互联网 发布:php 积分商城 编辑:程序博客网 时间:2024/05/18 23:15

  //汉字EnCode

.h
 int UniToUTF8(CString strUnicode,char *szUtf8);
 CString UniToUrlEncode(const char* szEncode);

.cpp

 

int CWeatherPropertyDlg::UniToUTF8(CString strUnicode,char *szUtf8)
{
 //MessageBox(strUnicode);
 int ilen = WideCharToMultiByte(CP_UTF8, 0, (LPCTSTR)strUnicode, -1, NULL, 0, NULL, NULL);
 char *szUtf8Temp=new char[ilen + 1];
 memset(szUtf8Temp, 0, ilen +1);
 WideCharToMultiByte (CP_UTF8, 0, (LPCTSTR)strUnicode, -1, szUtf8Temp, ilen, NULL,NULL);
 //size_t a = strlen(szUtf8Temp);
 sprintf(szUtf8, "%s", szUtf8Temp);//
 
 delete[] szUtf8Temp;
 return ilen;
}

CString CWeatherPropertyDlg::UniToUrlEncode(const char* szEncode)
{
 CString strEncoded;
 static const char szUnsafe[] = {"/<>%//^[]`+$,@:;/!#?=&" };
 static const char szHexChr[] = {"0123456789ABCDEF"};
 int nLength = strlen(szEncode);

 for(int i = 0; i < nLength; i++)
 {
  TCHAR ch = szEncode[i];

  if((NULL == strchr(szUnsafe, ch))
   && ((int)ch > 32)
   && ((int)ch < 123))
  {
   strEncoded += ch;
  }
  else
  {
   strEncoded += CString("%");
   strEncoded += szHexChr[(int)((ch >> 4) & 0x0f)];
   strEncoded += szHexChr[(int)(ch & 0x0f)];
  }
 }
 return strEncoded;
 }

 

测试:

 CString strTmp1 = _T("广州");
 GetDlgItemText(IDC_EDIT1,strTmp1);
 char *szChar = new char[strTmp1.GetLength()+1];
 UniToUTF8(strTmp1,szChar);
 UniToUrlEncode(szChar);

delecte[] szChar;

 

注意事项:

szChar要分配内存空间,要不在后面UniToUTF8()中的sprintf()操作中就会报错,原因就是第一个参数没有分配内存空间。也可在UniToUTF8()中对第一个参数进行判断,如果长度为0,则分配内存空间。

char *szChar = new char[strTmp1.GetLength()+1];

 

原创粉丝点击