gpt4 book ai didi

string - Delphi函数用于测试位置x处的字符串

转载 作者:行者123 更新时间:2023-12-03 18:57:11 24 4
gpt4 key购买 nike

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

if (pos('needle', haystack) = 1) then ...


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

令我惊讶的是,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;


进行一些错误检查。

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

最佳答案

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

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


如果性能真的很关键,那么您希望就地执行比较而不创建副本,从而执行堆分配。您可以为此使用 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;


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

关于string - Delphi函数用于测试位置x处的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26634377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com