DelphiXE Ansi字符串UTF-8编码判断


本文整理自网络,侵删。

 
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-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(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 在richedit中插入gif图片的方法

Delphi memo1 行倒序排列三种方法

Delphi xe5 for android ttabcontrol 控件

Delphi xe6 android视频采集

Delphi 在unicodestring中使用utf-8字符串

Delphi源码基础源码-按下回车取得焦点

如何将string变量赋值给pchar变量

Delphi repeat until 随机插入

Delphi bmp转换png

Delphi多线程

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...