场景:
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;
con