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 |
AnsiChar |
|
A character type guaranteed to be 8 bits in size |
PAnsiString |
|
Pointer to an AnsiString value |
String |
|
A data type that holds a string of characters |
WideString |
|
A data type that holds a string of WideChars |
|
|
|
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
WriteLn('String1 = '+string1);
WriteLn('String2 = '+string2);
end;
|
Show full unit code |
String1 = Hello
String2 = Hello World, how is everyone?
|
|