Delphi 转码

402 阅读1分钟

`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..4E00..9FA5
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 s1, s2: string; begin s1 := 'DELPHI爱好者'; s2 := '\u0044\u0045\u004c\u0050\u0048\u0049\u7231\u597d\u8005'; Edit1.Text := ChineseToUniCode(s1); { 汉字到 UniCode 编码 } Edit2.Text := UnicodeToChinese(s2); { UniCode 编码到汉字 } end;`