• Status: Solved
• Priority: Medium
• Security: Public
• Views: 185

I need to create a array of words from a string

Hello guys

I have a string with this value:

Str := 'house bees dogs cats sea'

I would like to get all words and put it in an array, this way:

V[0]:= house
V[1]:= bees
V[2]:= dogs
V[3]:= cats
V[4]:= sea

How could I do that?
thanks
0
hidrau
• 2
3 Solutions

Senior DeveloperCommented:
you can easily put them into a stringlist instead

var
sl: tstringlist;
begin

sl := tstringlist.create;
sl.text := stringreplace( str, ' ', #13#10, [rfReplaceAll]);

finally
sl.free;
end;

or if you have delphi7 you can do
sl.Delimiter := ' ';
sl.DelimitedText := str;
0

Senior DeveloperCommented:
to do it with an open ended array you can do

procedure TForm1.Button1Click(Sender: TObject);
const
str = 'this is a test';
var
myarray: array of string; //open ended array
i: integer;
spacefound: integer;
fullstr, partstr: string;
begin
fullstr := trim(str);

spacefound := pos(' ', fullstr);
while spacefound > 0 do
begin
partstr := copy(fullstr, 1, spacefound-1);
delete(fullstr, 1, spacefound);
fullstr := trim(fullstr); // in case there are 2 spaces in a row
setlength(myarray, length(myarray)+1);
myarray[length(myarray)-1] := partstr; //zero based
spacefound := pos(' ', fullstr);
end;
if fullstr <> '' then
begin
setlength(myarray, length(myarray)+1);
myarray[length(myarray)-1] := fullstr;
end;

// now display them

for i := 0 to length(myarray)-1 do
begin
memo1.lines.add(inttostr(i) + ' - ' + myarray[i]);
end;
end;
0

Commented:
This should do exactly ehat you want:

var list: TStringList;
myArray: array of String;
i: integer;

list := TStringList.create();
ExtractStrings([' '], [], PAnsiChar(myString), list);

setLength(myArray, list.Count);

for i := 0 to list.Count-1 do
myArray[i] := list.Strings[i];

//where myString is the string you want to split
0

Author Commented:
Thanks guys

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.