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

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

找了半天也没找到Delphi语言直接可用的UTF-8编码判断的代码

以下代码摘抄改编于
http://bbs.csdn.net/topics/370095245
#7 用户id: xiaoc1026
回答的C++代码

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;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值