delphi - 帮助扩展功能

标签 delphi function

我找到了一个函数,该函数可以提取两个其他词之间的词,并且效果很好,但是我想扩展该函数,以便它扫描我选择的整个字符串,并提取两个关键词之间的所有词,而不是只是它涉及的第一个。我猜想我需要添加某种循环,但是我是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; 


谢谢,
艾米莉

最佳答案

您可以在函数中添加其他参数:

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;

关于delphi - 帮助扩展功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061535/

相关文章:

php - 如何从 3 个表中获取数据?功能

function - 如何在 PostgreSQL 函数的插入查询中插入参数值?

javascript - 错误 var 未定义 - 但在使用之前已定义 -

Python 全局函数,如 'print'

delphi - 使用Delphi获取默认网关

performance - Delphi优化: constant loop

objective-c - Delphi double 型到 Objective C double 型

delphi - 无效的浮点运算调用Trunc()

php - 只能调用一次的函数

windows - 如何在 Windows 中获取有关串行 (COM) 端口的特定信息?