Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a Unicode string to an AnsiString?

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

like image 764
vico Avatar asked Dec 05 '13 14:12

vico


1 Answers

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>.

like image 132
David Heffernan Avatar answered Oct 31 '22 18:10

David Heffernan