Difference between Ansistring, Widestring, Unicodestring, Shortstring and String and how to convert

Asked

Viewed 10,937 times

5

During my Delphi learning I see implementations that use AnsiString,WideString, UnicodeString,ShortString and String but I don’t know the difference between them.

Another thing that always occurs to me is that I try to save some kind in another and it returns me the error that must be converted, however I always have difficulty to do it the right way.

1 answer

6


  • AnsiString: string composed of ASCII characters. Each Char has exactly 1 bytes. A pointer to a AnsiString (^AnsiString) amounts to char* in C;

  • WideString: exists only for compatibility with Windows. Each Char has 2 bytes, and must be used in Win32 functions with parameters LPWSTR, performing a cast for PWChar;

  • UnicodeString: Unicode string. By default UTF-16 (or at least it was when I last searched), but can assume other encodings such as UTF-8.

  • ShortString: equals old Pascal string, with its limitation of 255 characters.

  • String: in the newer versions of Delphi (2007 onwards), UnicodeString. In the old days it amounted to AnsiString.

So much AnsiString how much UnicodeString are more than a simple array of Char, they have code page information and size. However, to facilitate the cast of these types to PChar and its variations, this information is in the addresses previous to the returned by the operator @.

Conversion

The conversion between them is done automatically. Only care that should be taken, is that data may be lost during conversion due to type not supporting any feature of source string.

For example, convert UnicodeString for AnsiString, there may be loss due to Unicode characters occupying more than 1 byte.

Conversion of AnsiString (or UnicodeString) for ShortString, there will be data loss if the source string is greater than 255 (Length(origem) > 255).

  • Regarding the conversions between them you know how to tell me how they work?

  • I forgot! I edited the answer.

  • 1

    Grateful friend :D

  • 1

    Please, the ShortString that you said correspond to string ancient of Pascal but with 255 characters only, she is then of the type AnsiString (with 255 characters only)?

  • 2

    @Jamestk Yes: the string is equal to ShortString, and the AnsiString is equal to ShortString but without the limitation of 255 characters. Therefore, a AnsiString may contain a ShortString, but a ShortString may not necessarily contain a AnsiString.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.