2007. október 27., szombat

Finding a substring in a TStrings


Problem/Question/Abstract:

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:

{Purpose  : Binary search algorithm for a
            TStrings object. Finds the first
            occurence of any substring within
            a TStrings object or descendant}

function IndexOfSubString(List: TStrings; SubString: string): Integer;
var
  I,
    LowIdx,
    HighIdx: Integer;
  Found: boolean;
begin
  Found := false;
  Result := -1;
  {This type of search uses the first half
   of the TStrings list, so initialize the
   LowIdx and HighIdx to the first and approximate
   half of the list, respectively.}
  LowIdx := 0;
  HighIdx := List.Count div 2;

  {Note that Found and the LowIdx are used
   as conditionals. It's obvious why Found
   is used, but less apparent why LowIdx is
   used instead of HighIdx. The reason for
   this is that the way I've set it up here,
   HighIdx will never exceed (List.Count - 2),
   whereas LowIdx can equal (List.Count - 1)
   by nature of the assignment
   if Found remains false after the for loop.}
  while not Found and (LowIdx < (List.Count - 1)) do
  begin
    for I := LowIdx to HighIdx do
      if (Pos(SubString, List[I]) > 0) and
        not Found then
      begin
        Found := true;
        Result := I;
      end;

    if not Found then
    begin
      LowIdx := HighIdx + 1;
      HighIdx := HighIdx + ((List.Count - HighIdx) div 2);
    end;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése