Pages

Friday, October 31, 2014

How to implode array in delphi

As in the previous post how to explode some string in delphi, we can also make the reverse, it is implode. In delphi we can make implode function as in php.

Below is the function:

//////////////////////////////////////////////////////////////////////////
// Procedure - implode
// Author    - Ronald Buster
// Remarc    - PHP like implode function
//
// Returns a string containing a string representation of all the array
// elements in the same order, with the glue string between each element.
//////////////////////////////////////////////////////////////////////////

function implode(const glue: string; const pieces: array of string): string;
var
  I: Integer;
begin
  Result := '';
  for I := 0 to High(Pieces) do
    Result := Result + Glue + Pieces[I];
  Delete(Result, 1, Length(Glue));
end;

To use function above you can copy the sample code below :

procedure TForm1.Button1Click(Sender: TObject);
var
  ls_glue:string;
  arr_fruit:array[0..3] of string;
begin
  ls_glue := ', ';
  arr_fruit[0] := 'banana';
  arr_fruit[1] := 'mango';
  arr_fruit[2] := 'pear';
  arr_fruit[3] := 'orange';

  ShowMessage('Here are my favourite fruit: ' + implode(ls_glue, arr_fruit));
end;
Thanks to Ronald Buster for this function
Don't Forget To Join Our Community
×
Widget