Title: String functions
Question: I need to split a string like 'FIRST SECOND LAST' and return a part of it. How?
ex NthString('FIRST SECOND LAST',1,'#32') = 'SECOND'
&
I need to get the value of a data type in a string that looks like 'Machine="FLE400" Address="2" Batch="3450"'
ex: GetDataValue('Machine="FLE400" Address="2" Batch="3450"' ,'Address') = "2"
Answer:
Below are the functions used in the question above.
Note that the Nth index is a zero-index.. In other words, Nth = 0 will return the first string part.
function NthString(Str : string; Nth : integer; Separator : string) : string;
var lp0,sln,currn : integer;
InSep,FirstFound : boolean;
begin
result := '';
CurrN := 0;
InSep := false;
FirstFound := false;
sln := length(Str);
for lp0 := 1 to sln do begin
if Pos(Str[lp0],Separator) 0 then begin
if not InSep then begin
if FirstFound then inc(CurrN);
end;
InSep := true;
if CurrN Nth then break;
end else begin
InSep := false;
FirstFound := true;
if CurrN = Nth then result := result + Str[lp0];
end;
end;
end;
function GetDataValue(Source : string; Data : string) : string;
const CtrlChars = #61#34#39;
var lp0,sln,dfnd : integer;
InQuot,Valfnd : boolean;
begin
result := '';
InQuot := false;
Valfnd := false;
dfnd := Pos(uppercase(Data),uppercase(Source));
if (dfnd 0) then begin
sln := length(Source);
for lp0 := dfnd to sln do begin
if Pos(Source[lp0],CtrlChars) 0 then begin
if Valfnd then begin
if (Source[lp0] = #34) or (Source[lp0] = #39) then begin
if InQuot then break else InQuot := true;
end;
end;
if Source[lp0] = #61 then ValFnd := true;
end else begin
if Valfnd then begin
if InQuot then result := result + Source[lp0];
end;
end;
end;
end;
end;