我喜欢Sertac's idea
删除用括号括起来的字符串,然后再搜索一个字符串。这是通过搜索整个单词和区分大小写扩展的代码示例:
function ContainsWord(const AText, AWord: string; AWholeWord: Boolean = True;
ACaseSensitive: Boolean = False): Boolean;
var
S: string;
BracketEnd: Integer;
BracketStart: Integer;
SearchOptions: TStringSearchOptions;
begin
S := AText;
BracketEnd := Pos(']', S);
BracketStart := Pos('[', S);
while (BracketStart > 0) and (BracketEnd > 0) do
begin
Delete(S, BracketStart, BracketEnd - BracketStart + 1);
BracketEnd := Pos(']', S);
BracketStart := Pos('[', S);
end;
SearchOptions := [soDown];
if AWholeWord then
Include(SearchOptions, soWholeWord);
if ACaseSensitive then
Include(SearchOptions, soMatchCase);
Result := Assigned(SearchBuf(PChar(S), StrLen(PChar(S)), 0, 0, AWord,
SearchOptions));
end;
这是该函数的优化版本,它使用指针字符迭代而不进行字符串操作。与以前的版本相比,这可以处理缺少右括号的字符串的情况,例如My [favorite color is
. 由于缺少括号,此类字符串在那里被评估为 True。
原则是逐个字符地遍历整个字符串,当你找到左括号时,看看那个括号本身是否有一个右对。如果是,则检查从存储位置到左括号的子字符串是否包含搜索到的单词。如果是,则退出该功能。如果没有,请将存储的位置移动到右括号。如果左括号没有自己的右括号,则从存储的位置到整个字符串的末尾搜索单词并退出函数。
有关此代码的注释版本,请点击此链接。
function ContainsWord(const AText, AWord: string; AWholeWord: Boolean = True;
ACaseSensitive: Boolean = False): Boolean;
var
CurrChr: PChar;
TokenChr: PChar;
TokenLen: Integer;
SubstrChr: PChar;
SubstrLen: Integer;
SearchOptions: TStringSearchOptions;
begin
Result := False;
if (Length(AText) = 0) or (Length(AWord) = 0) then
Exit;
SearchOptions := [soDown];
if AWholeWord then
Include(SearchOptions, soWholeWord);
if ACaseSensitive then
Include(SearchOptions, soMatchCase);
CurrChr := PChar(AText);
SubstrChr := CurrChr;
SubstrLen := 0;
while CurrChr^ <> #0 do
begin
if CurrChr^ = '[' then
begin
TokenChr := CurrChr;
TokenLen := 0;
while (TokenChr^ <> #0) and (TokenChr^ <> ']') do
begin
Inc(TokenChr);
Inc(TokenLen);
end;
if TokenChr^ = #0 then
SubstrLen := SubstrLen + TokenLen;
Result := Assigned(SearchBuf(SubstrChr, SubstrLen, 0, 0, AWord,
SearchOptions));
if Result or (TokenChr^ = #0) then
Exit;
CurrChr := TokenChr;
SubstrChr := CurrChr;
SubstrLen := 0;
end
else
begin
Inc(CurrChr);
Inc(SubstrLen);
end;
end;
Result := Assigned(SearchBuf(SubstrChr, SubstrLen, 0, 0, AWord,
SearchOptions));
end;