string 中是否有汉字

来源:互联网 发布:windows cmd 编辑:程序博客网 时间:2024/05/02 18:08

// 返回 -1表示没有汉字 其它值表示第一个汉字在字符串中的位置
 int find_first_of_chinese_character(const std::string & source)
 {
  bool find = false;

  int i= 0 ;
  for(i=0; i< source.length()-1; i++)
  {
   unsigned char c = source[i];

   // 第一字节> =0xB0   &&   第二字节> =0xA1
   if(unsigned char(source[i]) >= 0xB0 && unsigned char (source[i+1]) >= 0xA1)
   {
    find = true;
    break;
   }  
  }

  return find ? i : -1; 
 }

 // 返回 -1表示没有汉字 其它值表示最后一个汉字在字符串中的位置
 int find_last_of_chinese_character(const std::string & source)
 {
  bool find = false; 
  int i= 0 ;
  for(i=source.length()-1; i > 0; i--)
  {
   unsigned char c = source[i];

   // 第一字节> =0xB0   &&   第二字节> =0xA1
   if(unsigned char(source[i]) >= 0xB0 && unsigned char (source[i+1]) >= 0xA1)
   {
    find = true;
    break;
   }  
  }
  
  return find ? i : -1; 
 }

原创粉丝点击