用于测试位置 x 处存在的字符串的 Delphi 函数

Mic*_*ent 2 delphi string delphi-6

在最近的一个涉及通过串行链接接收字符串的应用程序中,我发现自己编写了如下代码:

if (pos('needle', haystack) = 1) then ...
Run Code Online (Sandbox Code Playgroud)

为了检查特定的子字符串是否位于字符串的开头。

让我惊讶的是 pos 函数对此并不理想,因为它不知道我要在哪个位置查找子字符串。

有没有一个好的功能可以做到这一点?

有没有更通用的函数,例如IsSubStringAt(needle, haystack, position)

我确实考虑过使用这样的东西:

function IsSubstrAt(const needle, haystack: string; position: Integer): Boolean;
var
  ii: integer;
begin
  result := true;
  for ii := 1 to length(needle) de begin
    if (haystack[poition + ii -1] <> needle[ii]) then begin
      result := false;
      break;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

进行一些错误检查。

我希望找到一个现成的答案。

Dav*_*nan 5

由于您只想查看一个位置,因此您可以只形成子字符串并对其进行测试。像这样:

function IsSubStringAt(const needle, haystack: string; position: Integer): Boolean;
var
  substr: string;
begin
  substr := Copy(haystack, position, Length(needle));
  Result := substr = needle;
end;
Run Code Online (Sandbox Code Playgroud)

如果性能确实很关键,那么您可能希望就地执行比较,而不创建副本,从而执行堆分配。你可以用AnsiStrLComp这个。

function IsSubStringAt(const needle, haystack: string; position: Integer): Boolean;
begin
  if Length(haystack) - position + 1 >= Length(needle) then begin
    Result := AnsiStrLComp(
      PChar(needle), 
      PChar(haystack) + position - 1, 
      Length(needle)
    ) = 0;
  end else begin
    Result := False;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

如果要不区分大小写地进行检查,请在第一个版本中替换为=SameText在第二个版本中替换AnsiStrLComp为。AnsiStrLIComp