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

后端 未结 2 1526
我寻月下人不归
我寻月下人不归 2021-01-06 16:48

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

相关标签:
2条回答
  • 2021-01-06 17:13

    If you are using Delphi 2009 or higher, you should let the RTL do the conversion for you:

    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;
    

    If you are using Delphi 2007 or earlier, you can still do the conversion, just let the OS do it for you:

    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;
    
    0 讨论(0)
  • 2021-01-06 17:23

    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));

    0 讨论(0)
提交回复
热议问题