DelphiFAQ Home Search:
General :: Programming :: Delphi :: Strings
Algorithms for string handling problems, implemented in Delphi but useful for any procedural language.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Fastest way to search a string in a file

The function below returns position of substring in file, or -1 if such substring can not be found.

Better: use the Boyer-Moore algorithm. There's a Pascal implementation at
http://www.dcc.uchile.cl/~rbaeza/handbook/algs/7/713b.srch.p.html.

function PosInFile(Str,FileName:string):integer;
 var
    Buffer : array [0..1023] of char;
    BufPtr,BufEnd:integer;
    F:File;
    Index : integer;
    Increment : integer;
    c : char;
 
 function NextChar : char;
  begin
    if BufPtr>=BufEnd then
    begin
      BlockRead(F,Buffer,1024,BufEnd);
      BufPtr := 0;
      Form1.ProgressBar1.Position := FilePos(F);
      Application.ProcessMessages;
    end;
    Result := Buffer[BufPtr];
    Inc(BufPtr);
  end;
 
  begin
    Result := -1;
    AssignFile(F,FileName);
    Reset(F,1);
    Form1.ProgressBar1.Max := FileSize(F);
    BufPtr:=0;
    BufEnd:=0;
    Index := 0;
    Increment := 1;
    repeat
      c:=NextChar;
      if c=Str[Increment] then
        Inc(Increment)
      else
      begin
        Inc(Index,Increment);
        Increment := 1;
      end;
      if Increment=(Length(Str)+1) then
      begin
        Result := Index;
        break;
      end;
    until BufEnd = 0;
    CloseFile(F);
    Form1.ProgressBar1.Position := 0;
  end;

Generated 4:01:27 on Feb 25, 2017