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 锁定鼠标移动范围

Delphi pchar与string互转

Delphi写文本文件

Delphi中补齐字符串长度

Delphi webbrowser1遍历网页中的图片

Delphi读取utf8格式ini及取得动态�热�

Delphi10.2.3实现http异步下载

Delphi 获取其他进程句柄的几种方法

Delphi pascal实现二分查找算法

Delphi savelog 方便的记录日志

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



打赏

取消

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

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

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

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

评论

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