【发布时间】:2016-02-10 08:36:05
【问题描述】:
我有一个关于必须将 UTF8 字符串转换为 ANSI 字符串的代码的问题。我的代码适用于元音中的重音符号,但对于字母 Ñ 它不起作用。代码破坏了字符串。我该如何解决这个错误?
我在 UTF8 中的字符串:EDIFICIO PEÑAS BLANCAS
如果正确,我将在 ANSI 中使用的字符串:EDIFICIO PEÑAS BLANCAS
我现在在 ANSI 中的字符串:EDIFICIO 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;
谢谢。
【问题讨论】:
-
什么Delphi版本? - 最佳解决方案取决于它。添加适当的标签。
-
您拥有的第一个字符串未显示为 UTF-8。它是 UTF-8 编码的字节被解释为别的东西,可能是 ISO-8859-1 或 Windows-1252。如果您首先将 UTF-8 字节解释为 UTF-8,那么您可能不会遇到这个问题。您应该调查的是
Source的来源以及错误的原因。 -
这听起来很像你问错了问题并陷入了经典的 XY 问题。
标签: delphi utf-8 delphi-2010 ansistring