Link to home
Start Free TrialLog in
Avatar of electrodude102
electrodude102Flag for United States of America

asked on

how can i split this string?

im new to delphi...
 i have a string like this  " 123|asd1|fhgj2|er3|45678| " 
and i need to split it up.
i figured out how to do it IF it has different separators (eg " %123|asdf*fhgj^er|) like this
textin := %123|asdf|fhgj|er|45678|
 text1 := copy(textin, 1, pos('%', textin)-1);
  Delete(textin, 1, pos('%', textin)-1);
 text2 := copy(textin,1 ,pos('|', textin)-1);
  Delete(textin, 1, pos('|', textin)-1);
...
  L := Form2.ListView1.Items.Add;
  L.Caption := info;
  L.SubItems.Add(text1);
  L.SubItems.Add(text2);
ect

but how do i do it if the separators are the same?


ASKER CERTIFIED SOLUTION
Avatar of Usurpatirus
Usurpatirus
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You just have to loop the code you have there and it will work. I used ShowMessage to test if it works but I have also given you the code to add it to the listview in comments.
textin := '123|asdf|fhgj|er|45678';
while (pos('|', textin) > 0) do
begin
  text1 := copy(textin, 0, pos('|', textin)-1);
  Delete(textin, 1, pos('|', textin));
 
 
//  L := Form2.ListView1.Items.Add;
//  L.Caption := info;
//  L.SubItems.Add(text1);
ShowMessage(text1);
ShowMessage(textin);

Open in new window

sorry did not copy the end;
textin := '123|asdf|fhgj|er|45678';
while (pos('|', textin) > 0) do
begin
  text1 := copy(textin, 0, pos('|', textin)-1);
  Delete(textin, 1, pos('|', textin));
 
 
//  L := Form2.ListView1.Items.Add;
//  L.Caption := info;
//  L.SubItems.Add(text1);
  ShowMessage(text1);
  ShowMessage(textin);
end;

Open in new window

Avatar of electrodude102

ASKER

Graceful_Penguin: that works but i need a var(?) for each "set" of the string (not sure how to explain it..)
 
example: if the string in was '123|asdf|fhgjer|45678' it does this
text0 := 123
text1 := asdf
text2 := fhgjer
text3 := 45678

(cause i need to use them later, get it?)
The easiest way is to use a stringlist to store the strings but if you don't like that you can use a dynamic array. Here is the source for the string list. Just remember to destroy it when you are done.
var textin, text1 : string;
 Strings : TStringlist;
 counter : integer;
begin
   textin := '123|asdf|fhgj|er|45678';
   Strings := TStringlist.Create;
   counter := 0;
while (pos('|', textin) > 0) do
begin
  Strings.Add(copy(textin, 0, pos('|', textin)-1));
  Delete(textin, 1, pos('|', textin));
 
 
//  L := Form2.ListView1.Items.Add;
//  L.Caption := info;
//  L.SubItems.Add(text1);
   ShowMessage(Strings[counter]);
   ShowMessage(textin);
   inc(counter);

Open in new window

im going to accept Usurpatirus answer cause after messing around with it it seems he most usable, thanks you all your help