Unicode下汉字URLEncode解决方法

  //汉字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];

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhang11wu4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值