How can I convert a Unicode string to an AnsiString?

vico picture vico · Dec 5, 2013 · Viewed 28.3k times · Source

Trying to move project from Delphi 2007 to Delphi XE4. What is the best way to convert String to AnsiString in Delphi XE4?

Answer

David Heffernan picture David Heffernan · Dec 5, 2013

You simply assign it:

var
  AnsiStr: AnsiString;
  Str: string;
....
AnsiStr := Str;

The compiler will emit a warning mind you:

W1058 Implicit string cast with potential data loss from 'string' to 'AnsiString'

You can use a cast to suppress that warning:

AnsiStr := AnsiString(Str);

By default that gives no warning, although there is of course still potential for data loss. If you enable warning W1060 then the compiler says:

W1060 Explicit string cast with potential data loss from 'string' to 'AnsiString'

Of course, it's not expected that Delphi XE4 code has much place for the use of AnsiString. Unless you have a very specific interop requirement, then text is best held in the native data type, string. If you want to operate on byte arrays use TBytes or TArray<Byte>.