使用字符串函数读取分隔的文本文件

时间:2018-09-11 06:39:04

标签: delphi delphi-2010

我下面有一个带有示例数据的文本文件,以#分隔符分隔。

Calcium Carbonate#Calcium Carbonate is used as a source of calcium and to control acidity.
EDTA#EDTA stands for Ethylene Diamine Tetra Acetic acid and is used as a preservative.
Green Tea#Green Tea is made from the leaves of the Camellia sinensis plant.

我使用以下解决方案从文件中读取数据:

procedure TForm1.cmbIngredQ1_4Change(Sender: TObject);
var
 t: TextFile;
 sLine, sIngredient, sDescription, sFind: String;
 iIndex: Integer;
 bFound: boolean;
begin
try
 AssignFile(t, 'ingredients.txt');
 sFind := cmbIngredQ1_4.Items[cmbIngredQ1_4.ItemIndex];
 Reset(t);
 bFound := false;
 mmoOutput.Lines.Clear;
while (NOT EOF(t)) AND (bFound = false) do
begin
 Readln(t, sLine);
 iIndex := Pos('#', sLine);
 sIngredient := copy(sLine, 1, iIndex - 1);
 sDescription := copy(sLine, iIndex + 1);
 if sIngredient = sFind then
  begin
   bFound := true;
   mmoOutput.Lines.Add(sDescription);
  end;
end;
CloseFile(t);
except
 ShowMessage('File does not exist');
Exit;
end

如果在文本文件中添加了其他字段,请这样说:

 Calcium Carbonate#Calcium Carbonate is used as a source of calcium and to control#CaCO3
 EDTA#EDTA stands for Ethylene Diamine Tetra Acetic acid and is used as a  preservative#C10H16N2O8

是否存在一种解决方案,该解决方案使我可以使用相同的#delimiter读取数据的第三个字段,如果添加了第四个字段和第五个字段,则可以读取?注意:我知道一个字符串列表解决方案,但希望使用Pos,Copy和LastDelimiter之类的字符串函数找到一个解决方案。

0 个答案:

没有答案