微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Delphi:像Python一样编码字符串

我想像 Python那样对字符串进行编码.

Python代码是这样的:

def EncodetoUTF(inputstr):
  uns = inputstr.decode('iso-8859-2')
  utfs = uns.encode('utf-8')
  return utfs

这很简单.

但是在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;

输入是:“á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,PAnsiChar(inputstr),Length(inputstr),nil,0);
  if ret < 1 then Exit;
  SetLength(uns,ret);
  MultiBytetoWideChar(28592,PWideChar(uns),Length(uns));
  ret := WideCharToMultiByte(65001,Length(uns),nil);
  if ret < 1 then Exit;
  SetLength(Result,ret);
  WideCharToMultiByte(65001,PAnsiChar(Result),Length(Result),nil);
end;

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;

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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐