delphiutf-8delphi-2010ansistring

Converting UTF8 to ANSI (ISO-8859-1) in Delphi


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?

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

The code is here:

    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;

Thanks.


Solution

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

    This way: Utf8toAnsi(convertir_utf8_ansi(source));