Linux下C获取UTF-8字符串的真实长度
(2018-09-06 14:10:08)
标签:
linuxutf8 |
分类: linux |
最近在测试中发现,strlen获取带中文字符的字符串的长度值不正确,导致后续处理出现问题,所以根据网上的说法单独写了一个函数,测试可以通过。在此记录一下。
int i = 0;
int pos = 0;
int add = 0;
if(str == NULL)
return -1;
for(i = 0;i < len;
i++)
{
if(str[pos] & 1<<7)
{
if(str[pos] & 1<<6)
{
if(str[pos] &
1<<5)
{
if(str[pos] & 1<<4) //0x1111
0xxx
{
add +=
3;
pos +=
4;
continue;
}
//0x1110 xxxx
add += 2;
pos += 3;
continue;
}
//0x110x xxxx
add += 1;
pos += 2;
continue;
}
}
else //if(str[pos] & 1<<7)
{
pos++;
continue;
}
}
return len+add;
//获取UTF-8格式字符串的实际长度
//UTF-8编码格式:
//
编码
长度(Byte)
//
1
2
3
4
//0xxxxxxx
1
//110xxxxx 10xxxxxx
2
//1110xxxx 10xxxxxx
10xxxxxx
3
//11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4
int get_utf8_length(const char *str, int len)
{
}