Re: comparing string with strings

Posted by Henry on April 16, 2006

In Reply to comparing string with strings posted by john on April 11, 2006

I use the code below to get the last line from a text file.
My q? How can i compare this line with the other lines in the file? if the line finds a match then stop(do nothing), if it doesn't then post to Memo1.Text
function ReadFile(FileName:string):string;
var
  F:TextFile;
  S:string;
begin
  if FileExists(FileName) then begin
    AssignFile(F, FileName);
    Reset(F);
    while not EOF(F) do begin
      ReadLn(F, S);
      Result:=S;
    end;
    CloseFile(F);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Text := ReadFile( 'C:/File.txt');
end;

If I understand you well, the function ReadFile should return the last line of the file, if that line is not found anywhere else in the file. This is done in the example below. If the last line is found somewhere else in the file, the function returns an empty string. Also returns empty string if the text file is not found.

function TForm1.ReadFile(FileName: string): string;
var
  List: TStringList;
  LastLine: string;
  i: integer;
begin
  Result := '';
  if FileExists(FileName) then begin
    List := TStringList.Create;
    List.LoadFromFile(FileName);
    LastLine := List[List.Count - 1];
    Result := LastLine;
    for i := 0 to List.Count - 2 do begin
      if List[i] = LastLine then begin
        Result := '';
        break;
      end;
    end;
    List.Free;
  end
  else
    ShowMessage('File not found: ' + FileName);
end;

Related Articles and Replies