Recent

Author Topic: How to split a string and get values from the string?  (Read 762 times)

Doe

  • New Member
  • *
  • Posts: 17
How to split a string and get values from the string?
« on: January 24, 2021, 12:55:45 pm »
Hello, guys. I was trying to split a text in a memo, for example, "distance = 10" or "distance=10". The string should be split by "=" or " =" and get the value behind it, but my code doesn't assign the value to the related variables. How to solve this problem.
My codes are below:
Code: Pascal  [Select][+][-]
  1. var
  2.   Form1: TForm1;
  3.   i:integer;
  4.   A: TStringArray;
  5.   toxt: string;
  6.   dist,time:string;
  7.  
  8. procedure TForm1.Button1Click(Sender: TObject);
  9. begin
  10.     for i:=0 to memo1.lines.count-1 do
  11.     begin
  12.        text:=memo1.lines[i];
  13.        If (Pos(' = ',toxt)>0) then
  14.        begin
  15.        A := toxt.Split(' = ');
  16.        if (A[0]='distance') then
  17.        begin
  18.        dist:=A[3];
  19.        end
  20.        else if A[0]='time' then
  21.        begin
  22.        time:=A[3];
  23.        end
  24.        else
  25.        if (Pos(' = ',toxt)=0) then
  26.        begin
  27.        A := toxt.Split('=');
  28.        if A[0]='distance' then
  29.        begin
  30.        dist:=A[3];
  31.        end
  32.        else if A[0]='time' then
  33.        begin
  34.        time:=A[3];
  35.        end
  36.        end;
  37.     end;
  38. end;
  39.     showmessage(dist);
  40.     showmessage(time);
  41. end;
  42. end.
  43.  
« Last Edit: January 24, 2021, 01:11:36 pm by Doe »

PascalDragon

  • Hero Member
  • *****
  • Posts: 5446
  • Compiler Developer
Re: How to split a string and get values from the string?
« Reply #1 on: January 24, 2021, 01:01:11 pm »
Please use code tags to avoid the forum software messing up your code.

wp

  • Hero Member
  • *****
  • Posts: 11857
Re: How to split a string and get values from the string?
« Reply #2 on: January 24, 2021, 01:09:22 pm »
The Lines propety of a memo is a descendant of TStrings and thus inherits the handling of name=value pairs implemented by TStrings. Simply use the Values[name] property which returns the value part after the '=':
Code: Pascal  [Select][+][-]
  1. var
  2.   distance: Double;
  3.   time: Double;
  4.   h: Double;
  5. begin
  6.   distance := StrToFloat(Memo1.Lines.Values['distance']);
  7.   time := StrToFloat(Memo1.Lines.Values['time']);
  8.   h := StrToFloat(Memo1.Lines.Values['height']);  

Doe

  • New Member
  • *
  • Posts: 17
Re: How to split a string and get values from the string?
« Reply #3 on: January 24, 2021, 01:13:50 pm »
Thanks a lot!

Bart

  • Hero Member
  • *****
  • Posts: 5275
    • Bart en Mariska's Webstek
Re: How to split a string and get values from the string?
« Reply #4 on: January 24, 2021, 08:30:49 pm »
IIRC then you asked the same question a few days ago.

Bart

 

TinyPortal © 2005-2018