[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 161
  • Last Modified:

Array Function

I need an array function that will take a string and then split the string into the array elements by a specified separator. The function would return the filled array.

I can write the function, my problem is declaring the function and using the function. I thought it could be written as:

function ParseData(dataLine: String; sep: String): Array of String;

then the use of the array would be:

parsedArray := ParseData(dataLine, sep);

I get all sorts of errors when trying the above. Can someone show me how to utilize arrays as parameters and results?

Thanks in advance,
Chad
0
dhertzfe
Asked:
dhertzfe
  • 2
  • 2
1 Solution
 
dhertzfeAuthor Commented:
Edited text of question.
0
 
MotazCommented:
Hello Chad, you can change it to procedure and you have to pass the array result as a parameter, the procedure header will be:

procedure ParseArray(dataLine: String; sep: String; var x: array of string);

you can call it as:


var
  MyArray: Array of string;
begin
  ParseArray('This is a test', ' ',
    MyArray);

Motaz

0
 
MotazCommented:
Instead of using array of string you have to use TStringList, the full function is :

procedure GetToken(DataLine: string; sep: char; var x: TStringList);
var
  i: Integer;
begin
  i:= 0;
  if DataLine[Length(DataLine)] <> Sep then
    DataLine:= DataLine + Sep;
  repeat
    x.Add(Copy(DataLine, 1, Pos(Sep, DataLine) - 1));
    Delete(DataLine, 1, Pos(Sep, DataLine) );
  until DataLine = '';

end;


procedure TForm1.Button1Click(Sender: TObject);
var
  List: TStringList;
begin
  List:= TStringList.Create;
  GetToken('First,Second,Third,Last', ',', List);
  Memo1.Lines:= List;

end;

Motaz
0
 
dhertzfeAuthor Commented:
Thanks Motaz,

This helps alot.

Chad
0
 
MadshiCommented:
If you have D4 or D5, you can also use this (which is quite near to your first try):

type
  TDAString = array of string;  // dynamic array of string

function ParseData(dataLine, sep: String): TDAString;
begin
  // something like this:
  SetLength(result, 10);
  result[0] := 'firstElement';
  result[1] := 'secondElement';
  // ...
end;

var parsedArray : TDAString;

parsedArray := ParseData(dataLine, sep);
for i1 := 0 to high(parsedArray) do
  ShowMessage(parsedArray[i1]);

Regards, Madshi.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now