栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++中可正确获取UTF-8字符长度的函数分享

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++中可正确获取UTF-8字符长度的函数分享

在C++的char*以及string中,使用的是字节流编码,即sizeof(char) == 1。

也就是说,C++是不区分字符的编码的。

而一个合法UTF8的字符长度可能为1~4位。

现在假设一串输入为UTF8编码,如何能准确的定位到每个UTF8字符的“CharPoint”,而不会错误的分割字符呢?

参考这个页面:http://www.nubaria.com/en/blog/?p=289

可以改造出下面的函数:

const unsigned char kFirstBitMask = 128; // 1000000
const unsigned char kSecondBitMask = 64; // 0100000
const unsigned char kThirdBitMask = 32; // 0010000
const unsigned char kFourthBitMask = 16; // 0001000
const unsigned char kFifthBitMask = 8; // 0000100
 
int utf8_char_len(char firstByte)
{
  std::string::difference_type offset = 1;

  if(firstByte & kFirstBitMask) // This means the first byte has a value greater than 127, and so is beyond the ASCII range.
  {  
    if(firstByte & kThirdBitMask) // This means that the first byte has a value greater than 224, and so it must be at least a three-octet code point.
    {  
      if(firstByte & kFourthBitMask) // This means that the first byte has a value greater than 240, and so it must be a four-octet code point.
 offset = 4;
      else
 offset = 3;
    }  
    else
    {  
      offset = 2;
    }  
  }  
  return offset;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/65621.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号