在Delphi中将UTF8转换为ANSI(ISO-8859-1)
我有一个关于必须将UTF8字符串转换为ANSI字符串的代码的问题。我的代码适用于元音中的重音,但对于字母ñ则不起作用。代码将断开字符串。我怎样才能纠正这个错误 我在UTF8中使用的字符串:大厦PEÃ’AS BLANCAS在Delphi中将UTF8转换为ANSI(ISO-8859-1),delphi,utf-8,delphi-2010,ansistring,Delphi,Utf 8,Delphi 2010,Ansistring,我有一个关于必须将UTF8字符串转换为ANSI字符串的代码的问题。我的代码适用于元音中的重音,但对于字母ñ则不起作用。代码将断开字符串。我怎样才能纠正这个错误 我在UTF8中使用的字符串:大厦PEÃ’AS BLANCAS 如果正确的话,我在ANSI中使用的字符串是:buildicio PEñAS BLANCAS 我现在在ANSI中使用的字符串是:大厦PE 代码如下: function TFormMain.convertir_utf8_ansi(const Source: string):
如果正确的话,我在ANSI中使用的字符串是:buildicio PEñAS BLANCAS
我现在在ANSI中使用的字符串是:大厦PE
代码如下:
function TFormMain.convertir_utf8_ansi(const Source: string):string;
var
Iterator, SourceLength, FChar, NChar: Integer;
begin
Result := '';
Iterator := 0;
SourceLength := Length(Source);
while Iterator < SourceLength do
begin
Inc(Iterator);
FChar := Ord(Source[Iterator]);
if FChar >= $80 then
begin
Inc(Iterator);
if Iterator > SourceLength then break;
FChar := FChar and $3F;
if (FChar and $20) <> 0 then
begin
FChar := FChar and $1F;
NChar := Ord(Source[Iterator]);
if (NChar and $C0) <> $80 then break;
FChar := (FChar shl 6) or (NChar and $3F);
Inc(Iterator);
if Iterator > SourceLength then break;
end;
NChar := Ord(Source[Iterator]);
if (NChar and $C0) <> $80 then break;
Result := Result + WideChar((FChar shl 6) or (NChar and $3F));
end
else
Result := Result + WideChar(FChar);
end;
end;
函数TFormMain.convertir\u utf8\u ansi(常量源代码:string):string;
变量
迭代器,SourceLength,FChar,NChar:Integer;
开始
结果:='';
迭代器:=0;
SourceLength:=长度(源);
而迭代器=80美元,则
开始
公司(迭代器);
如果迭代器>源长度,则中断;
FChar:=FChar和$3F;
如果(FChar和$20)为0,则
开始
FChar:=FChar和$1F;
NChar:=Ord(源[迭代器]);
如果(NChar和$C0)$80,则中断;
FChar:=(FChar shl 6)或(NChar和3F美元);
公司(迭代器);
如果迭代器>源长度,则中断;
结束;
NChar:=Ord(源[迭代器]);
如果(NChar和$C0)$80,则中断;
结果:=结果+宽字符((FChar shl 6)或(NChar和$3F));
结束
其他的
结果:=结果+宽字符(FChar);
结束;
结束;
谢谢。如果您使用的是Delphi 2009或更高版本,您应该让RTL为您进行转换:
type
Latin1String = type AnsiString(28591); // codepage 28591 = ISO-8859-1
var
utf8: UTF8String;
latin1: Latin1String;
begin
utf8 := ...; // your source UTF-8 string
latin1 := Latin1String(utf8);
end;
如果您使用的是Delphi 2007或更早版本,您仍然可以进行转换,只需让操作系统为您进行转换:
var
utf8: UTF8String;
latin1: AnsiString;
ws: WideString;
len: Integer;
begin
utf8 := ...; // your source UTF-8 string
len := MultiByteToWideChar(CP_UTF8, 0, PAnsiChar(utf8), Length(utf8), nil, 0);
SetLength(ws, len);
MultiByteToWideChar(CP_UTF8, 0, PAnsiChar(utf8), Length(utf8), PWideChar(ws), len);
len := WideCharToMultiByte(28591, 0, PWideChar(ws), Length(ws), nil, 0, nil, nil);
SetLength(latin1, len);
WideCharToMultiByte(28591, 0, PWideChar(ws), Length(ws), PAnsiChar(latin1), len, nil, nil);
end;
除了我拥有的函数外,我还通过调用内部函数UTF8toAnsi解决了这个问题。我正在开发Delphi2010 这样:
Utf8toAnsi(转换器(源代码)) 什么Delphi版本最优解取决于它。添加适当的标记。您的第一个字符串没有显示为UTF-8。这是UTF-8编码的字节被解释为其他内容,可能是ISO-8859-1或Windows-1252。如果您首先将UTF-8字节解释为UTF-8,则可能不会出现此问题。你应该调查的是
源代码从哪里来以及为什么它是错误的。听起来你问错了问题,陷入了经典的XY问题。