在Delphi中将UTF8转换为ANSI

在Delphi中将UTF8转换为ANSI

本文介绍了在Delphi中将UTF8转换为ANSI(ISO-8859-1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对将UTF8字符串转换为ANSI字符串的代码有疑问。我的代码适用于元音中的重音,但字母Ñ无效。该代码将字符串中断。如何解决这个错误?

I have a question about a code that i have to convert UTF8 strings to ANSI strings. My code works for accents in vowels, but with letter Ñ it doesn't work. The code breaks the string. How can I fix this mistake?

我在UTF8中使用的字符串:EDIFICIOPEÃ'ASBLANCAS

如果正确,我在ANSI中使用的字符串:EDIFICIOPEÑASBLANCAS

我现在在ANSI中具有的字符串:EDIFICIO PE

The string I have in UTF8: EDIFICIO PEÑAS BLANCAS
The string I would have in ANSI if correct: EDIFICIO PEÑAS BLANCAS
The string I have in ANSI now: 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;

谢谢。

推荐答案

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

I solved the issue invoking, apart from the function that i had, the internal function UTF8toAnsi. I'm working on Delphi 2010.

这种方式:
Utf8toAnsi(con​​vertir_utf8_ansi(source));

This way:Utf8toAnsi(convertir_utf8_ansi(source));

这篇关于在Delphi中将UTF8转换为ANSI(ISO-8859-1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:28