场景:
1. 分析数据时,获取到的数据是字符串,但是有可能不是正确的完整的utf8字符串,打印出来或输出到文件时表现出来的就是显示乱码.
这时候就需要过滤掉非法字符使utf8字符串能正确显示, 比如把非法字符替换为#
代码:
1. 这个函数的特性是1个个字符判断, 适合任意长度,任意构造的 utf8 (无效)字符串.
bool IREUtil::FilterUtf8(unsigned char * string,int length)
{
if(!string)
{
return false;
}
unsigned char * bytes = string;
unsigned char * end = bytes+length;
//10xxxxxx 应该出现个数
int count_s = 0;
//10xxxxxx 剩余个数
int minus_s = 0;
while(bytes != end)
{
if(bytes[0] > 0xF7)
{
if(minus_s)
{
int m = count_s-minus_s+1;
memset((void*)(bytes-m),'#',m);
}
minus_s = 0;
count_s = 0;
bytes[0] = '#';
bytes+=1;
continue;
}
if(bytes[0] <= 0x7F)
{
if(minus_s)
{
int m = count_
当遇到不完整或错误的UTF8字符串导致乱码时,可以使用代码过滤非法字符,将其替换为#。该方法适用于任意长度和构造的UTF8字符串。
订阅专栏 解锁全文
846

被折叠的 条评论
为什么被折叠?



