Show: Delphi C++
Display Preferences

Declaring and Initializing Strings

From RAD Studio
Jump to: navigation, search

Go Up to Working with 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:

  S: string;
  S[i];    // this will cause an access violation
  // statements

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:

  S: string;   // empty string
  proc(PChar(S));  // be sure that proc can handle nil
  // statements

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);

See Also

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions