设为首页 加入收藏

TOP

c++ 对汉字进行url编码(实验管用)
2012-12-02 22:34:15 】 浏览:547
Tags:汉字 进行 url 编码 实验 管用

CString urlEncode(CString s)
{

 int len = s.GetLength();
 char *out = new char[len*9+1];
 memset(out , 0 , len*9+1);
 int i , j;
 int ch = 0 ;

 static char  myhex[0xFF+1][4];  //add by zhouzd 2008-10-06
 static bool isinital = false;

 if ( !isinital )
 {
  for ( i = 0 ; i <= 0xFF ; ++i )
  {
   myhex[i][0] = '%';
   sprintf( myhex[i]+1 , "%02X" , i );
  }
  isinital = true;
 }

 for (i = 0 , j = 0; i < len ; ++i )
 {
  ch = s.GetAt(i);

  //printf("%c\n" , s.GetAt(i) );

  if ('A' <= ch && ch <= 'Z')         // 'A'..'Z'
  {
   out[j++] = ch;
  }
  else if ('a' <= ch && ch <= 'z')    // 'a'..'z'
  {
   out[j++] = ch;
  }
  else if ('0' <= ch && ch <= '9')    // '0'..'9'
  {
   out[j++] = ch;
  }
  else if (ch == ' ')           // space
  {
   out[j++] = '+';
  }
  else if (ch == '-' || ch == '_'        // 不需要转化
   || ch == '.' || ch == '!'
   || ch == '~' || ch == '*'
   || ch == '\'' || ch == '('
   || ch == ')')
  {
   out[j++] = ch;
  }
  else if (ch <= 0x007f)     // ASCII控制字符
  {   
   strcat(out , myhex[ch]);
   j += 3;
  }
  else if (ch <= 0x07FF)         // 非ASCII <= 0x7FF
  {
   strcat(out , myhex[0xc0 | (ch >> 6)]);
   strcat(out , myhex[0x80 | (ch & 0x3F)]);
   j += 6;
  }
  else                       // 0x7FF < ch <= 0xFFFF
  {
   strcat(out , myhex[0xe0 | (ch >> 12)]);
   strcat(out , myhex[0x80 | ((ch >> 6) & 0x3F)]);
   strcat(out , myhex[0x80 | (ch & 0x3F)]);
   j += 9;
  }
 }
 out[j] = '\0';
 USES_CONVERSION;
 CString result = A2W(out);

 delete out;
 out = NULL;

 return result;
}

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇移动开发多平台代码共享 下一篇c++做的供其他程序使用的动态链接..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目