dur*_*ara 5 delphi encode utf character-encoding
我想像Python那样对字符串进行编码.
Python代码是这样的:
def EncodeToUTF(inputstr):
uns = inputstr.decode('iso-8859-2')
utfs = uns.encode('utf-8')
return utfs
Run Code Online (Sandbox Code Playgroud)
这很简单.
但是在Delphi中,我不明白,如何编码,先强制好字符集(无论我们拥有哪台计算机).
我试过这个测试代码来看转换:
procedure TForm1.Button1Click(Sender: TObject);
var
w : WideString;
buf : array[0..2048] of WideChar;
i : integer;
lc : Cardinal;
begin
lc := GetThreadLocale;
Caption := IntToStr(lc);
StringToWideChar(Edit1.Text, buf, SizeOF(buf));
w := buf;
lc := MakeLCID(
MakeLangID( LANG_ENGLISH, SUBLANG_ENGLISH_US),
0);
Win32Check(SetThreadLocale(lc));
Edit2.Text := WideCharToString(PWideChar(w));
Caption := IntToStr(AnsiCompareText(Edit1.Text, Edit2.Text));
end;
Run Code Online (Sandbox Code Playgroud)
输入是:"árvíztűrőtükörfúrógép",匈牙利口音测试词组.当地的lc是1038(hun),新的lc是1033.
但这次每次都会得到0个结果(相同的字符串),并且重音是相同的,我不会丢失ŐŰ这不是英语朗.
我做错了什么?我如何做与Python相同的事情?
感谢您的帮助,链接等:dd
Windows对ISO-8859-2使用代码页28592.如果您有一个包含ISO-8859-2编码字节的缓冲区,则必须先将字节解码为UTF-16,然后将结果编码为UTF-8.根据您使用的Delphi版本,您可以:
1)在D2009之前,使用MultiByteToWideChar()和WideCharToMultiByte():
function EncodeToUTF(const inputstr: AnsiString): UTF8String;
var
ret: Integer;
uns: WideString;
begin
Result := '';
if inputstr = '' then Exit;
ret := MultiByteToWideChar(28592, 0, PAnsiChar(inputstr), Length(inputstr), nil, 0);
if ret < 1 then Exit;
SetLength(uns, ret);
MultiByteToWideChar(28592, 0, PAnsiChar(inputstr), Length(inputstr), PWideChar(uns), Length(uns));
ret := WideCharToMultiByte(65001, 0, PWideChar(uns), Length(uns), nil, 0, nil, nil);
if ret < 1 then Exit;
SetLength(Result, ret);
WideCharToMultiByte(65001, 0, PWideChar(uns), Length(uns), PAnsiChar(Result), Length(Result), nil, nil);
end;
Run Code Online (Sandbox Code Playgroud)
2a)在D2009 +上,使用SysUtils.TEncoding.Convert():
function EncodeToUTF(const inputstr: RawByteString): UTF8String;
var
enc: TEncoding;
buf: TBytes;
begin
Result := '';
if inputstr = '' then Exit;
enc := TEncoding.GetEncoding(28592);
try
buf := TEncoding.Convert(enc, TEncoding.UTF8, BytesOf(inputstr));
if Length(buf) > 0 then
SetString(Result, PAnsiChar(@buf[0]), Length(buf));
finally
enc.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)
2b)在D2009 +上,或者定义一个新的字符串typedef,将数据放入其中,并将其分配给UTF8String变量.无需手动编码/解码,RTL将为您处理所有事情:
type
Latin2String = type AnsiString(28592);
var
inputstr: Latin2String;
outputstr: UTF8String;
begin
// put the ISO-8859-2 encoded bytes into inputstr, then...
outputstr := inputstr;
end;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3120 次 |
最近记录: |