将Western代码页转换为Windows 1251

时间:2015-07-28 19:12:19

标签: delphi

我尝试加载Cyrillic网页(默认代码页Western)并将其放入TMemo组件。

但我在备忘录中看到“Âûñòàâêè”而不是“Выставки”。

如何将字符串从Western转换为Windows 1251代码页?

Delphi XE 8 sp1

2 个答案:

答案 0 :(得分:1)

XE8中的

TMemo(以及大多数RTL / VCL / FMX)需要UTF-16格式的UnicodeString数据。您必须将网页数据从其实际字符集(可能已经是Windows-1251,因为在Windows-1252中编码俄语文本没有意义)解码为UTF-16,然后再将其加载到{{ 1}}。用于原始数据的实际字符集需要在HTTP TMemo标头或HTML本身中报告。

您不会将原始数据解码为Windows 1251.仅当您使用在使用Windows-1251的Windows俄语计算机上运行应用程序的前Unicode版本的Delphi(2007及更早版本)时,才需要这样做。它的默认代码页。那些日子在像XE8这样的Unicode环境中消失了。

Delphi预装了Indy。 Indy的Content-Type组件为您处理charset-to-UTF16解码,例如:

TIdHTTP

如果您以任何其他方式下载网页数据,则必须将其作为原始字节下载并自行解码,例如使用Memo1.Text := IdHTTP1.Get(URL); 后跟TEncoding.GetEncoding(1251)。或者,如果字节位于TEncoding.GetString(),您可以使用TStream指定Memo1.Lines.LoadFromStream()作为编码。

答案 1 :(得分:-2)

type
  TSrcStr = type AnsiString(1251);
  TDstStr = type AnsiString(1252);

function Decode(const s: string): string;
var
  a: TSrcStr;
  b: TDstStr;
begin
  setlength(a, length(s));
  b := s;
  move(b[low(b)], a[low(a)], length(b)*sizeof(b[low(b)]));
  result := a;
end;

procedure Test;
var
  s: string;
begin
  s := 'Âûñòàâêè';
  s := Decode(s);
  Assert(s='Выставки');
end;