Delphi-UniCode转汉字(\u 格式)、汉字转UniCode(\u 格式)

发布时间 2023-04-02 14:23:14作者: 疯狂delphi

 

相关资料:

https://www.cnblogs.com/guorongtao/p/14729102.html          Delphi UniCode转汉字(\u 格式)、汉字转UniCode(\u 格式)

实例代码

1、UniCode转汉字

function UnicodeToChinese(sStr: string): string;
var
  i: Integer;
  index: Integer;
  temp, top, last: string;
begin
  index := 1;
  while index >= 0 do
  begin
    index := Pos('\u', sStr) - 1;
    if index < 0 then         //非 unicode编码不转换 ,自动过滤
    begin
      last := sStr;
      Result := Result + last;
      Exit;
    end;
    top := Copy(sStr, 1, index); // 取出 编码字符前的 非 unic 编码的字符,如数字
    temp := Copy(sStr, index + 1, 6); // 取出编码,包括 \u,如\u4e3f
    Delete(temp, 1, 2);
    Delete(sStr, 1, index + 6);
    Result := Result + top + WideChar(StrToInt('$' + temp));
  end;
end;

2、汉字转UniCode  

function ChineseToUniCode(sStr: string): string;     //汉字的 UniCode 编码范围是: $4E00..$9FA5     作者:滔Roy
var
  w:Word;
  hz:WideString;
  i:Integer;
  s:string;
begin
  hz:=sStr;
  for i:=1 to Length(hz) do begin
    w := Ord(hz[i]);
    s:=IntToHex(w, 4);
    Result := Result +'\u'+ LowerCase(s);
  end;
end;

3、示例:

var
s,s1,s2 : string;
begin
s1 := '滔Roy';
s2 := '\u6ed4\u0052\u006f\u0079';

s:=ChineseToUniCode(s1); {汉字到 UniCode 编码}
s:=UnicodeToChinese(s2); { UniCode 编码到汉字}
end;