3

我有一个关于必须将 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;

谢谢。

4

2 回答 2

13

如果您使用的是 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;
于 2015-11-09T21:21:37.403 回答
4

除了我拥有的函数之外,我还解决了调用内部函数 UTF8toAnsi 的问题。我正在研究 Delphi 2010。

这样:Utf8toAnsi(convertir_utf8_ansi(source));

于 2015-11-11T12:38:34.080 回答