RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.SetString Function

Sets the contents and length of the given string.

Pascal
procedure SetString(var s: string; buffer: PChar; len: Integer);
C++
SetString(AnsiString s, const char * buffer, int len);

In Delphi code, SetString sets the contents and length of the given string variable to the block of characters given by the Buffer and Len parameters.  

For a short string variable, SetString sets the length indicator character (the character at S[0]) to the value given by Len and then, if the Buffer parameter is not nil, copies Len characters from Buffer into the string starting at S[1]. For a short string variable, the Len parameter must be a value between 0 and 255.  

For a long string variable, SetString sets S to reference a newly allocated string of the given length. If the Buffer parameter is not nil, SetString then copies Len characters from Buffer into the string; otherwise, the contents of the new string is left uninitialized. If there is not enough memory available to create the string, an EOutOfMemory exception is raised. Following a call to SetString, S is guaranteed to reference a unique string, that is a string with a reference count of one.  

Delphi Examples: 

 

{
The following code demostrates the use of ReallocMem function. Three
edit boxes and a button are expected onthe form.
}
function FastStrCat(const S1, S2: String): String;
var
  FinalStr: PChar;
begin
  {
   Allocated enough space in FinalStr to copy the contents
   of the initial string + $00 character
  }
  GetMem(FinalStr, (Length(S1) + 1) * SizeOf(Char));

  { Copy the contents of the first string }
  MoveChars(S1[1], FinalStr^, Length(S1) + 1);

  { And now expand the final string + $00 character }
  ReallocMem(FinalStr, (Length(S1) + Length(S2) + 1) * SizeOf(Char));

  { Copy the contents of the second string }
  MoveChars(S2[1], FinalStr[Length(S1)], Length(S2) + 1);

  { Get the result in String }
  SetString(Result, FinalStr, Length(S1) + Length(S2));
  FreeMem(FinalStr);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  { Concatenate 2 string }
  Edit3.Text := FastStrCat(Edit1.Text, Edit2.Text);
end;

 

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