帮助扩展功能

时间:2010-10-31 02:06:35

标签: delphi function

我发现了一个函数,它将提取一个在2个其他单词之间的单词,这很有效,但我想扩展该函数,以便扫描我选择的整个字符串并提取所有在2之间的单词关键字,而不仅仅是它的第一个。我猜我需要添加一些循环,但我是Delphi的新手所以我不知道我需要做什么,我可以使用一些帮助。

无论如何这里是我正在谈论的功能。


function GetAWord(sentence, word1, word2 : string) : string;
  var
    n : integer;
  begin
  n := pos(word1, sentence);
  if n = 0 then begin
    result := '';
    exit;
  end;
  delete(sentence, 1, n + length(word1) - 1);
  n := pos(word2, sentence);
  if n = 0 then begin
    result := '';
    exit;
  end;
  result := copy(sentence, 1, n - 1);
  end; 

谢谢你, 艾米丽

1 个答案:

答案 0 :(得分:1)

您可以在函数中添加一个额外的参数:

function GetAWord(sentence, word1, word2 : string; Index: Integer) : string;
var
  N: integer;

begin
  repeat
    N:= pos(word1, sentence);
    if N = 0 then begin
      result := '';
      exit;
    end;
    delete(sentence, 1, n + length(word1) - 1);
    n := pos(word2, sentence);
    if n = 0 then begin
      result := '';
      exit;
    end;
    Dec(Index);
    if Index < 0 then begin
      result := copy(sentence, 1, n - 1);
      Exit
    end;
    delete(sentence, 1, n + length(word2) - 1);
  until False;
end;


// test
procedure TForm1.Button1Click(Sender: TObject);
const
  S = '115552211666221177722';

begin
  ShowMessage(GetAWord(S, '11', '22', 0));
  ShowMessage(GetAWord(S, '11', '22', 1));
  ShowMessage(GetAWord(S, '11', '22', 2));
  ShowMessage(GetAWord(S, '11', '22', 4));
end;

您可以在一个功能中找到所有条目:

procedure ParseSentence(sentence, word1, word2 : string; Strings: TStrings);
var
  N: integer;

begin
  Strings.Clear;
  repeat
    N:= pos(word1, sentence);
    if N = 0 then exit;
    delete(sentence, 1, n + length(word1) - 1);
    n := pos(word2, sentence);
    if n = 0 then exit;
    Strings.Add(copy(sentence, 1, n - 1));
    delete(sentence, 1, n + length(word2) - 1);
  until False;
end;

procedure TForm1.Button2Click(Sender: TObject);
const
  S = '115552211666221177722';

var
  SL: TStringList;

begin
  SL:= TStringList.Create;
  ParseSentence(S, '11', '22', SL);
  Memo1.Lines.Assign(SL);
  SL.Free;
end;