DelphiBasics
AnsiString
Type
A data type that holds a string of AnsiChars System unit
type AnsiString;
Description
The AnsiString data type is used to hold sequences of characters, like sentences.
 
Each character is an AnsiChar, guaranteed to be 8 bits in size.
 
An AnsiString can hold any number of characters, restricted only by memory.
 
Unlike ShortStrings, AnsiStrings are pointer referenced variables. Storage is allocated for an AnsiString only when needed. For example, assigning the value of one AnsiString to another does not allocate storage for a copy of the first string. Instead, the reference count of the first string is incremented, and the second AnsiString set to point to it.
 
But when the second string is changed, new storage is obtained for this new string, and the reference count for the first string is decremented.
 
When a string is no longer referenced (the last AnsiString referer is set to nil), it is discarded. This is an example of Delphi managing storage on your behalf.
 
AnsiStrings can be assigned from other strings, from functions that return a string, and with concatenations as in the sample code.
Notes
Strings are indexed with 1 for the first character (arrays start with 0 for the first element).
Related commands
AnsiCharA character type guaranteed to be 8 bits in size
PAnsiStringPointer to an AnsiString value
StringA data type that holds a string of characters
WideStringA data type that holds a string of WideChars
 Download this web site as a Windows program.




 
Example code : Assign to two AnsiStrings and manipulate these
var
  string1, string2 : AnsiString;
begin
  // Assign a famous sentence to the first string
  string1 := 'Hello World';

  // Assign to the second string
  // This simply points string2 at string1
  // The 'Hello World' string storage has a reference count of 2
  string2 := string1;

  // Add to the second string
  // This disassociates from string1 - new string storage is
  // created to hold the string2 value
  string2 := string2 + ', how is everyone?';

  // And finally, set the length of the first string to 5
  SetLength(string1, 5);

  // Display both strings
  ShowMessage('String1 = '+string1);
  ShowMessage('String2 = '+string2);
end;
Show full unit code
  String1 = Hello
  String2 = Hello World, how is everyone?
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page