delphi - 从文本文件中读取特定行

标签 delphi pascal

假设我有一个文本文件,并且在其中(中间或其他地方)有以下几行:


我的名字:某人

我的年龄:17

我的学校:哈佛


没有针对他们的特定行号(随机),并且没有重复(“我的名字”仅显示一次,我的年龄也是如此……)

这不是我要查找的确切内容,但我认为它应该读取该特定行,但不是(它正在读取整个文件):

AssignFile(myFile, 'C:\Users\boss\Desktop\dude.txt');
myWord := 'My name : Someone';
Reset(myFile);

while not Eof(myFile) do
begin
  readln(myFile, myWord);
  writeln(myWord);
end;

CloseFile(myFile);


正如我所说的,这是在读取整个Textfile,我只是想让一些东西可以操作它,但我不能。

我想在“我的名字”之后阅读整行,这意味着名字每次都不会相同。

最佳答案

如果我按照您的意愿去做,那实际上很简单。

假设你有

var
  ALine,
  StartOfLineToFind,
  AValue : String;
  P : Integer;

  [...]
  StartOfLineToFind := 'My name :';


然后在你的循环中

    readln(myFile, ALine);
    if Pos(StartOfLineToFind, ALine) = 1 then begin  // see if the line starts with the label you're looking for
      AValue := Copy(ALine, Length(StartOfLineToFind), Length(ALine) - Length(StartOfLineToFind);  //  Copy the rest of the line after the label
      AValue := Trim(AValue);  //  remove the leading and trailing spaces
      writeln(AValue);
    end;

关于delphi - 从文本文件中读取特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37365649/

相关文章:

string - 多个字符串变量真的可以引用相同的数据吗?

delphi - 如何仅在 TVirtualStringtree 的 header 中显示提示?

delphi - 为什么 Delphi 编译器不针对重新定义的常量发出警告?

pascal - 手动字符串替换(Free Pascal)

delphi - 字符串到缓冲区的额外空格 Filestream.WriteBuffer 方法中隐式的 void 类型转换

delphi - 为什么 CTRL+C 在 TMemo 组件上不起作用? (Vista+德尔福7)

multithreading - 辅助线程如何结束应用程序?

delphi - Pascal,如何将整数标记为货币值

c - 如何从源代码编译 VTProlog?

c++ - 帕斯卡的模数