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