gpt4 book ai didi

delphi - 如何有效地检查一个字符串是否包含几个子字符串之一?

转载 作者:行者123 更新时间:2023-12-03 19:24:55 25 4
gpt4 key购买 nike

如何有效检查一个字符串是否包含一些子字符串之一?
假设我有一个字符串:

`Hi there, <B>my</B> name is Joe <DIV>.</DIV> Hello world. &nbsp;`


如何检查字符串是否包含 <B><DIV>&nbsp;

我可以做一个简单的:

Result := (Pos('<B>', S) > 0) or 
(Pos('<DIV>', S) > 0) or
(Pos('&nbsp;', S) > 0);


但这似乎效率很低,因为它使 N(最坏的情况)通过并且我的字符串很大。

最佳答案

更好的版本:

function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
CurrChr, C: PChar;
i, j, Ln: Integer;
begin
for i := 1 to Length(S) do
begin
CurrChr := @S[i];
for j := 0 to High(AnyOf) do
begin
C := @AnyOf[j][1]; // assume that no empty strings
if C^ <> CurrChr^ then
Continue;

Ln := Length(AnyOf[j]);
if (Length(S) + 1 - i) < Ln then // check bounds
Continue;

if CompareMem(C, CurrChr, Ln * SizeOf(C^)) then
Exit(True);
end;
end;

Exit(False);
end;


您还可以构建一些停止符号表并提高速度。这是一个复杂的话题,因此我建议您阅读例如 Bill Smyth "Computing Patterns in Strings"书。

关于delphi - 如何有效地检查一个字符串是否包含几个子字符串之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47700280/

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