delphi - 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.
解决方案
首先回忆一下是做什么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”的行
推荐阅读
- java - 在 Hadoop 上运行 jar 时如何解决 ConnectException?
- python - 将列表中的随机元素与 Python 中的用户输入连接起来
- javascript - 移除 Webpack 的模块包装器以生成纯 JS 脚本
- r - 我如何将所有这些箱线图“合并”到一个单一的箱线图中,值 > 0
- kotlin - 中缀 没有足够的信息来推断类型变量 T
- javascript - 为什么所有项目总是在 d3.js 中同时进入和退出选择
- javascript - 通过 js 提供指向 iframe 的链接
- discord - 带有 discord.py 的 Discordbot 不会使用命令 ctx.channel.purge(*amount*) 删除消息
- jestjs - 更改笑话测试输出(iTerm 很奇怪)
- c# - .NET MVC:在服务器上执行繁重的任务,然后在完成时向用户发送电子邮件,以便用户可以离开站点而不是等待?