计算含有汉字的字符串长度

/*计算含有汉字的字符串长度。

考点:字符串综合编程能力。

编写gbk_strlen函数,计算含有汉字的字符串的长度,汉字作为一个字符处理。已知汉字编码为双字节,其中首字节<0,尾字节在0~63以外(如果一个字节范围为-128~127)*/

#include <iostream>
using namespace std;

int gbk_strlen(const char* str)
{
 const char* p = str;       //p用于后面遍历
 
 while(*p)               //若是结束符0则结束循环
 {
  if (*p < 0 && (*(p+1)<0 || *(p+1)>63))  //中文汉字情况
  {               
   str++;         //str移动一位,p移动两位,因此长度加1
   p += 2;
  }
  else
  {
   p++;             //str不动,p移动一位,长度加1
  }
 }
 
 return (p-str);//返回地址之差
}
int main()
{
 char str[] = "abc你好123中国456";        //含有中文汉字的字符串
 
 int len = gbk_strlen(str);                   //获得字符串长度
 cout << str << endl;
 cout << "len = " << len << endl;
 
 return 0;
}

posted @ 2013-09-20 15:51  小菜美妞成长中  阅读(810)  评论(0编辑  收藏  举报