RAD Studio
ContentsIndex
PreviousUpNext
Declaring and Initializing Strings

When you declare a string:

S: string;

you do not need to initialize it. 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 characters
  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. 

String literals are Unicode by default. To initialize a string to ANSI characters, cast the literal:

AnsiString S;
S := AnsiString('Unicode string');

To obtain the length of a string in elements, use the Length function. Note that for MBCS and Unicode strings, this is not necessarily the number of characters. 

To obtain the length of a short string in bytes, use the SizeOf function. For the other string types, multiply Length by SizeOf. For instance, if S is a UnicodeString, its length in bytes is Length(S) * SizeOf(S)

Remember when declaring a string that:

  S: string[n];

implicitly declares a short string, not a string of n length. To declare a string of specifically n length, declare a variable of type string and use the SetLength procedure.

  S: string;
  SetLength(S, n);
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!