Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extract string

Status
Not open for further replies.

MARTINRODDY

Programmer
Apr 3, 2001
30
US
I have a string:

test_123;3400;0

I want to be able to extract the middle substring 3400
What is the best way to do this ????

Any advice appreciated
Martin
 
Check out faq218-360 in the pascal forum
S. van Els
SAvanEls@cq-link.sr
 
Martin, try this. Drop a button and an editbox on a form and try the following code.

type
DelimSet = set of Char;

function WordPos(N : Integer ; S : string; Delims : DelimSet) : Integer ;
var
ii,iLength,iCount : Integer;
begin
Result := 0; { default }
iLength := Length(S);
iCount := 0;
ii := 1;
while (ii <= iLength) and (iCount <> N) do begin
while (ii <= iLength) and (S[ii] in Delims) do
Inc(ii);

// Position should be start of next word
if ii <= iLength
then Inc(iCount);

// Are we at the nth word in the string ?
if iCount <> N
then while (ii <= iLength) and (not(S[ii] in Delims)) do
Inc(ii)
else WordPos := ii ;
end; { while }
end;

function GetWord(N : Byte; S : string ; Delims : DelimSet) : string;
var
ii, iLength : Integer ;
begin
Result := '' ; { default }
iLength := Length(S);
ii := WordPos(N, S, Delims);
if ii <> 0 { get the word starting at the position returned }
then while (ii <= iLength) and (not(S[ii] in Delims)) do
begin
Result := Result + s[ii] ;
Inc(ii);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
EditBox1.Text := GetWord(2,'test_123;3400;0',[';',' ',])
end;
 
Resolve it in logical steps

1) Search for the first delimiter in the target
2) if found store the index
3) kick the delimiter out
4) search for another delimiter in the remainder of the target
5) if found retrieve the substring from the original target
6) insert messages to check the function of your program

ingredients:
1) a form (of course)
2) an editbox
3) a label
4) a button



procedure TForm1.Button1Click(Sender: TObject);

var master1, master2, delimiter, found : string;
i, j : integer; //operating variables


begin
delimiter :=';';
master1:= edit1.Text;
i:= pos(delimiter, master1); //Step 1-2
if i > 0 then
begin
master2 := master1;
delete(master2,i,1); // Step 3
j:= pos(delimiter, master2); //Step 4
if j > 0 then
begin
j := j +1;
found := copy(master1,(i+1),(j-i-1)); //Step 5
label1.Caption := found;
end
else MessageDlg('No 2nd delimiter found',mtError,[mbOK],0);
end
else MessageDlg('No 1st delimiter found',mtError,[mbOK],0);
end;


Regards S. van Els
SAvanEls@cq-link.sr
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top