I have memo with unwanted character in lines, and I want to remove them all. Here is my code:
var
del: Integer;
begin
for del := 0 to m0.Lines.Count - 1 do
begin
if (AnsiContainsStr(m0.Lines[del], 'remove me')) then
begin
m0.Lines.Delete(del);
end;
end;
end;
With the code above still left some lines that i wanted to remove. It only delete some of them. So I tried with another approach and this is do the job.
var
i, r, n: Integer;
begin
for i := 0 to m0.Lines.Count - 1 do
begin
if (AnsiContainsStr(m0.Lines[i], 'remove me')) then
begin
for r := 0 to m0.Lines.Count - 1 do
begin
if (AnsiContainsStr(m0.Lines[r], 'remove me')) then
begin
for n := 0 to m0.Lines.Count - 1 do
begin
if (AnsiContainsStr(m0.Lines[n], 'remove me')) then
begin
m0.Lines.Delete(n);
end;
end;
m0.Lines.Delete(r);
end;
end;
m0.Lines.Delete(i);
end;
end;
end;
I think this is not right, and i should not do this. How to do such job elegantly ?
Because your loop runs from 0
to Count - 1
, the line after a deleted line will be skipped.
Explanation: suppose line 3 needs to get deleted. You delete it, and now line 4 will be line 3. The loop variable i
will be incremented to 4 on the next run, thus the new line 3 is never evaluated.
Solution: run your loop in reverse:
for i := m0.Lines.Count - 1 downto 0 do