Delphi 判断AnsiStr是否是UTF编码格式 IsUtf8Format
Delphi 判断AnsiStr是否是UTF编码格式 IsUtf8Format
//判断是否是UTF编码格式
function IsUtf8Format(AnsiStr: AnsiString): Boolean;
var
I, iCount, chr: Integer;
c: AnsiChar;
nBytes: Integer; // UFT-8可用1-6个字节编码,ASCII用一个字节
bAllAscii: Boolean; // 如果全部都是ASCII, 说明不是UTF-8
begin
Result := False;
nBytes := 0;
bAllAscii := True;
iCount := Length(AnsiStr);
for I := 1 to iCount do
begin
c := AnsiStr[I];
chr := Ord(c);
// 判断是否ASCII编码,如果不是,说明有可能是UTF-8,ASCII用7位编码,但用一个字节存,最高位标记为0,o0xxxxxxx;中文ASCII编码可能最高位为1
if (chr and $80) <> 0 then
bAllAscii := False;
// 如果不是ASCII码,应该是多字节符,计算字节数
if nBytes = 0 then
begin
if chr > $80 then
begin
if (chr>=$fc) and (chr<=$fd) then // 1111 1100 and 1111 1101
nBytes := 6
else if chr>=$f8 then // 1111 1000
nBytes := 5
else if chr>=$f0 then // 1111 0000
nBytes := 4
else if chr>=$e0 then // 1110 0000
nBytes := 3
else if chr>=$c0 then // 1100 0000
nBytes := 2
else Exit;
Dec(nBytes);
end;
end
else // 多字节符的非首字节,应为 10xxxxxx
begin
if (chr and $c0) <> $80 then Exit;
Dec(nBytes);
end;
end;
// 违返规则
if nBytes > 0 then
Exit;
// 如果全部都是ASCII, 说明不是 UTF-8
if bAllAscii then
Exit;
Result := True;
end;
C++
/*
* 判断字符串内指定字符数是否为utf8
* 输入
* const char *str: 要检查的字符串
* long length: 要检查的字符串的长度
* int nWords: 要检查的最大字符数
*/
BOOL CUtility::IsWordsUTF8(const char *str, long length, int nWords)
{
int i;
int nBytes=0;//UFT8可用1-6个字节编码,ASCII用一个字节
unsigned char chr;
BOOL bAllAscii=TRUE; //如果全部都是ASCII, 说明不是UTF-8
if ( -1 == nWords)
{
nWords = (int)length;
}
for(i=0;i<length;i++)
{
if (0 >= nWords)
{
return !bAllAscii;
}
chr= *(str+i);
if( (chr&0x80) == 0 ) // 判断是否ASCII编码,如果不是,说明有可能是UTF-8,ASCII用7位编码,但用一个字节存,最高位标记为0,o0xxxxxxx;中文ASCII编码可能最高位为1
nWords--;
else
bAllAscii= FALSE;
if(nBytes==0) //如果不是ASCII码,应该是多字节符,计算字节数
{
if(chr>=0x80)
{
nWords--;
if(chr>=0xFC&&chr<=0xFD)//1111 1100 1111 1101
nBytes=6;
else if(chr>=0xF8)//1111 1000
nBytes=5;
else if(chr>=0xF0)//1111 0000
nBytes=4;
else if(chr>=0xE0)//1110 0000
nBytes=3;
else if(chr>=0xC0)//1100 0000
nBytes=2;
else
{
return FALSE;
}
nBytes--;
}
}
else //多字节符的非首字节,应为 10xxxxxx
{
if( (chr&0xC0) != 0x80 )
{
return FALSE;
}
nBytes--;
}
}
if( nBytes > 0 ) //违返规则
{
return FALSE;
}
if( bAllAscii ) //如果全部都是ASCII, 说明不是UTF-8
{
return FALSE;
}
return TRUE;
}
创建时间:2021.04.09 更新时间:
博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你有所帮助,谢谢!
浙公网安备 33010602011771号