首页 > 解决方案 > Delphi通过TextFile循环特定字符串将该字符串复制到变量

问题描述

因此,包含“NVMEM”的行已成功从文本文件中删除。我实际上希望相反的情况发生,它将删除除包含字符串'NVMEM'的行之外的每一行。我尝试将按钮 2 的 for 循环下的 if 语句更改为 if not 语句,认为它会起作用,但它只会删除所有内容。有没有办法让我能够删除除包含字符串的行之外的所有行。

implementation

{$R *.dfm}

procedure TForm3.Button1Click(Sender: TObject);
var
NVE: TextFile;

begin
if not FileExists('NVE.txt') then
  begin
  AssignFile(NVE, 'NVE.txt');
  Rewrite(NVE);

  WriteLn(NVE, 'abcdefg') ;
  WriteLn(NVE, 'hijklmnop')      ;
  WriteLn(NVE, 'fmdiomfsa');
  WriteLn(NVE, 'heres the line with NVMEM'); //line I want to parse


  ShowMessage('You have successfully created the file amigo');
  CloseFile(NVE);

  end;


if FileExists('NVE.txt') then
  begin
    AssignFile(NVE,'NVE.txt');
    Rewrite(NVE);

    WriteLn(NVE, 'abcdefg') ;
    WriteLn(NVE, 'hijklmnop');
    WriteLn(NVE, 'hope i got that right');
    WriteLn(NVE, 'heres the line with NVMEM'); //line I want to parse

      ShowMessage('Eso Final');
      CloseFile(NVE);

  end;
end;

procedure TForm3.Button2Click(Sender: TObject);
var
NVE: string;
i : integer;
raw_data1,stringy: string;
raw_data: TstringList;
begin
  stringy := 'NVMEM';
  i := 0;
  raw_data := TStringlist.Create;
  try
    raw_data.LoadFromFile('NVE.txt');
    for i := raw_data.Count-1 downto 0 do
      if pos(stringy, raw_data[i])<>0 then
        raw_data.Delete(i);
    raw_data.SaveToFile('NVE.txt');
  finally
    raw_data.free;
  end;
end;



end.

标签: delphitext-files

解决方案


首先回忆一下是做什么function Pos(SubStr, Str: string): integer的。

`Pos()` returns the position of `SubStr` within `Str` if `SubStr` is included in `Str`.
`Pos()` returns 0 when `SubStr` is not included in `Str`. 

现在,对于要修改的这些代码行Button2Click()(其中i行的索引raw_data),以删除除包含“NVMEM”的行之外的所有行:

  if pos(stringy, raw_data[i]) <> 0 then  // your current code
    raw_data.Delete(i);

可以拼写为“如果 stringy 包含在 raw_data[i] 中,则删除 raw_data[i]”,这与您想要的相反。

把逻辑反过来,即“如果raw_data[i]中包含stringy,则删除raw_data[i]”,如下:

Pos()SubStr不包含时返回0 Str,故删除一行的条件应该是:

  if pos(stringy, raw_data[i]) = 0 then   // change `<>` to `=`
    raw_data.Delete(i);

这将使您在 中留下raw_data: TStringList一行,即包含“NVMEM”的行


推荐阅读