Bianca
Bianca

Reputation: 973

Show message if string not found in memo

procedure TForm1.bFAT1Click(sender: TObject);
    var
     FAT: Integer;
    begin
       for FAT := 0 to memo1.lines.Count - 1 do
        begin
          if AnsiContainsStr(memo1.lines[FAT], 'Olive Oil') then
          begin
          ShowMessage('Olive Oil exist!');
          end;
        end;
     // But  how to show message if integer is empty?        
    end;

I want to do something if no line contains 'Olive Oil'. How to do it?

Upvotes: 0

Views: 1027

Answers (1)

jpfollenius
jpfollenius

Reputation: 16610

What you need is an Exit statement to leave the procedure as soon as you found a matching element. That way, when you reach the end of the procedure, you know that you have not found a matching element:

for FAT := 0 to memo1.lines.Count - 1 do
begin
  if AnsiContainsStr(memo1.lines[FAT], 'Olive Oil') then
  begin
    ShowMessage('Olive Oil exist!')
    Exit;  // we can stop here since we found it       
  end;
end;

// we only come here if no line contained 'Olive Oil' (because of the EXIT)
ShowMessage('Olive Oil does not exist!');

Edit: (inspired by @David) It is good practice to separate your logic from the UI / display (for example ShowMessage). To do that you can define a function like this:

function IndexOfLineContaining(const Text : String; Lines : TStrings) : Integer;
begin
  for Result := 0 to Lines.Count - 1 do
    if AnsiContainsStr(Lines[Result], Text) then 
      Exit;
  Result := -1;
end;

On top of that you could easily define a boolean function:

function HasLineContaining(const Text : String; Lines : TStrings) : Boolean;
begin
  Result := (IndexOfLineContaining(Text, Lines) > -1);
end;

and use that to do your message display:

if HasLineContaining('Olive Oil', Memo1.Lines) then
  ShowMessage ('foo')
else
  ShowMessage ('bar');   

I suggest that you work a bit on your terminology to make your questions clearer. An integer cannot be empty and the sentence " do something if [FAT] do not found 'Olive Oil'." with FAT being an integer does not make any sense.

Upvotes: 2

Related Questions