提取多个子字符串

时间:2018-01-26 03:32:09

标签: string delphi

我有一个字符串123HEREWEGOMAMAMIAGOWILLYOULETMEGOMAMAMIATOLOVEYOUSOMAMAMIASOIHATEYOUMAMAMIAHEY如何获得所有可用的MAMAMIA + 2字符串长度?我需要:MAMAMIAGOMAMAMIASO

我的问题,在找到的最后一个子字符串给我错误的输出。它使用子串的长度呈现字符串的开头:123HEREWE而不是MAMAMIAGO

我正在使用this function

function Occurrences(const Substring, Text: string): Integer;
        var
          offset: Integer;
        begin
          Result := 0;
          offset := PosEx(Substring, Text, 1);

          while offset <> 0 do
          begin
            inc(Result);
            offset := PosEx(Substring, Text, offset + Length(Substring));
             memo1.Lines.Add(Copy(Text, offset, Length(Substring)+2));
          end;
        end;

我的程序

procedure TFH129.btn1Click(Sender: TObject);
var
  s: string;
  i: Integer;
begin
  s := '123HEREWEGOHEREWEGOMAMAMIAGOWILLYOULETMEGOMAMAMIATOLOVEYOUSOMAMAMIASOIHATEYOUMAMAMIAHEY00';
  i := Occurrences('MAMAMIA', s);
end;

3 个答案:

答案 0 :(得分:4)

您正在错误的位置添加匹配的文本,而不检查添加的匹配是否超过字符串长度。

进入procedure ExtractSubStringsPlus2(const SubString, SearchString: string; list: TStringList); // Extract found sub strings together with the next two characters into a list // Use StrUtils.PosEx if Delphi version is older than XE3 var offset,len: integer; begin list.Clear; len := Length(SubString); offset := Pos(Substring, SearchString, 1); while offset <> 0 do begin // Test if added length is past length of search string if (offset + len + 1 > Length(SearchString)) then break; // Copy found match list.Add(Copy(SearchString,offset,len+2)); // Continue search offset := Pos(Substring, SearchString, offset + len); end; end; 循环时,首先要检查添加的匹配是否超过搜索字符串长度。然后,您可以在开始新搜索之前添加匹配项。

"dependencies": {
    ...
    "jquery": "version_num",
    ...
}

答案 1 :(得分:1)

您的问题如下所述:

FUNCTION Occurrences(CONST SubString,Text : STRING): Cardinal;
  CONST
    HellFreezesOver     = FALSE;

  VAR
    OFS                 : Cardinal;

  BEGIN
    Result:=0; OFS:=0;
    REPEAT
      OFS:=PosEx(SubString,Text,OFS+1);
      // Here I terminate the loop, in case the string isn't found any more.
      IF OFS=0 THEN BREAK;
      INC(Result);
      Memo1.Lines.Add(COPY(Text,OFS,LENGTH(SubString)+2))
    UNTIL HellFreezesOver
  END;

请改用:

pymodbus3

答案 2 :(得分:0)

使用TstringList的一种非常简单的方法:

Var aList: TstringList;
    i: integer;
begin
  aList := TstringList.create;
  try
    aList.lineBreak := 'MAMAMIA';
    aList.text := 'x' + '123HEREWEGOMAMAMIAGOWILLYOULETMEGOMAMAMIATOLOVEYOUSOMAMAMIASOIHATEYOUMAMAMIAHEY';
    For I := 1 to aList.count-1 do
      if length(aList[i]) >=2 then memo1.Lines.Add(aList.lineBreak + Copy(aList[i], 1, 2));  
  finally
    aList.free;
  end;
end;