本文整理自网络,侵删。
IDE为DelphiXE
/// <summary>/// 判断字符串是否为 UTF-8 编码/// </summary>/// <param name="AnsiStr">输入字符串</param>/// <returns>输入是否为 UTF-8 编码</returns>function IsWordsUTF8(AnsiStr: AnsiString): Boolean;var I, iCount, chr: Integer; c: AnsiChar; nBytes: Integer; // UFT-8可用1-6个字节编码,ASCII用一个字节 bAllAscii: Boolean; // 如果全部都是ASCII, 说明不是UTF-8begin 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(False);
Dec(nBytes); end; end else // 多字节符的非首字节,应为 10xxxxxx begin if (chr and $c0) <> $80 then Exit(False);
Dec(nBytes); end; end; // 违返规则 if nBytes > 0 then Exit(False); // 如果全部都是ASCII, 说明不是 UTF-8 if bAllAscii then Exit(False);
Result := True;end;
相关阅读 >>
Delphi xe5 for android ttabcontrol 控件
Delphi 在unicodestring中使用utf-8字符串
更多相关阅读请进入《Delphi》频道 >>