Author: William Gerbert
How to find a substring in a TStrings
Answer:
The IndexOf function in TStrings is great because it lets you quickly get the index
of Item that holds the string in question. Unfortunately, it doesn't work for
sub-strings. In that case, I've put together a neat little function called
IndexOfSubString where you pass in the TStrings descendant you want to search on
and a search value, and it'll return the index. Check it out:
1 2 {Purpose : Binary search algorithm for a3 TStrings object. Finds the first4 occurence of any substring within5 a TStrings object or descendant}6 7 function IndexOfSubString(List: TStrings; SubString: string): Integer;
8 var9 I,
10 LowIdx,
11 HighIdx: Integer;
12 Found: boolean;
13 begin14 Found := false;
15 Result := -1;
16 {This type of search uses the first half17 of the TStrings list, so initialize the18 LowIdx and HighIdx to the first and approximate19 half of the list, respectively.}20 LowIdx := 0;
21 HighIdx := List.Count div 2;
22 23 {Note that Found and the LowIdx are used24 as conditionals. It's obvious why Found25 is used, but less apparent why LowIdx is26 used instead of HighIdx. The reason for27 this is that the way I've set it up here,28 HighIdx will never exceed (List.Count - 2),29 whereas LowIdx can equal (List.Count - 1)30 by nature of the assignment31 if Found remains false after the for loop.}32 whilenot Found and (LowIdx < (List.Count - 1)) do33 begin34 for I := LowIdx to HighIdx do35 if (Pos(SubString, List[I]) > 0) and36 not Found then37 begin38 Found := true;
39 Result := I;
40 end;
41 42 ifnot Found then43 begin44 LowIdx := HighIdx + 1;
45 HighIdx := HighIdx + ((List.Count - HighIdx) div 2);
46 end;
47 end;
48 end;