Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate array of string elements into a string

How should an array of string be converted into string (With separator char)? I mean, is there some system function I can use instead of writing my own function?

like image 774
Hwau Avatar asked May 10 '15 20:05

Hwau


People also ask

How do I combine string arrays into strings?

Using StringBufferCreate an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.

How do you join an array of strings in Python?

We can use python string join() function to join a list of strings.

Which of the following joins all elements of an array into a string?

join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).


2 Answers

Since you are using Delphi 2007 you have to do it you self:

function StrArrayJoin(const StringArray : array of string; const Separator : string) : string;
var
  i : Integer;
begin
  Result := '';
  for i := low(StringArray) to high(StringArray) do
    Result := Result + StringArray[i] + Separator;

  Delete(Result, Length(Result), 1);
end;

Simply traverse the array and concat it with your seperator.

And a small test example:

procedure TForm1.FormCreate(Sender: TObject);
begin
  Caption :=StrArrayJoin(['This', 'is', 'a', 'test'], ' ');
end;
like image 88
Jens Borrisholt Avatar answered Sep 21 '22 07:09

Jens Borrisholt


If you're using a more recent version of Delphi you could use TStringHelper.Join, see: http://docwiki.embarcadero.com/Libraries/Sydney/en/System.SysUtils.TStringHelper.Join

Writeln(String.Join(',', ['String1', 'String2', 'String3']));

Output would be: String1,String2,String3

like image 33
ArieKanarie Avatar answered Sep 21 '22 07:09

ArieKanarie