如果要从一个字符串中匹配某个指定字符串(即查找指定字符串是否在某个字符串中),那么除了按字符逐个搜索外,还有一个另类通俗的算法。下面请跟我来。
代码如下(仅给出DELPHI的实现):
function searchStr(beStr, subStr:
string
): Integer;
var
oldLength: integer;
tempStr: string ;
begin
oldLength : = Length(beStr);
tempStr : = StringReplace(beStr, subStr, ' | ' , [rfReplaceAll]);
if Length(tempStr) < oldLength then
begin
Result : = Pos( ' | ' , tempStr);
end
else
begin
Result : = - 1 ;
end;
end;
var
oldLength: integer;
tempStr: string ;
begin
oldLength : = Length(beStr);
tempStr : = StringReplace(beStr, subStr, ' | ' , [rfReplaceAll]);
if Length(tempStr) < oldLength then
begin
Result : = Pos( ' | ' , tempStr);
end
else
begin
Result : = - 1 ;
end;
end;
首先,取得要被搜索的字符串(这里为beStr)的长度
接着,使用StringReplace函数将需要搜索的字符串beStr中指定字符串(这里为subStr)替换为特殊的表示符(这里使用了“|”
最后,判断替换后的字符串是否发生了变化,如果变化说明存在相关匹配,可以使用pos函数来定位此匹配。
这个算法避免了繁杂的字符搜索和位置计算。