When you declare a long string:
S: string;
you do not need to initialize it. Long strings are automatically initialized to empty. To test a string for empty you can either use the EmptyStr variable:
S = EmptyStr;
or test against an empty string:
S = '';
An empty string has no valid data. Therefore, trying to index an empty string is like trying to access nil and will result in an access violation:
var S: string; begin S[i]; // this will cause an access violation // statements end;
Similarly, if you cast an empty string to a PChar, the result is a nil pointer. So, if you are passing such a PChar to a routine that needs to read or write to it, be sure that the routine can handle nil:
var S: string; // empty string begin proc(PChar(S)); // be sure that proc can handle nil // statements end;
If it cannot, then you can either initialize the string:
S := 'No longer nil';
proc(PChar(S));// proc does not need to handle nil now
or set the length, using the SetLength procedure:
SetLength(S, 100);//sets the dynamic length of S to 100 proc(PChar(S));// proc does not need to handle nil now
When you use SetLength, existing characters in the string are preserved, but the contents of any newly allocated space is undefined. Following a call to SetLength, S is guaranteed to reference a unique string, that is a string with a reference count of one. To obtain the length of a string, use the Length function.
Remember when declaring a string that:
S: string[n];
implicitly declares a short string, not a long string of n length. To declare a long string of specifically n length, declare a variable of type string and use the SetLength procedure.
S: string;
SetLength(S, n);
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|