findstr.m

来自「本书是电子通信类的本科、研究生辅助教材」· M 代码 · 共 30 行

M
30
字号
function k = findstr(s1,s2)
%FINDSTR finds one string within another.
%	K = FINDSTR(S1,S2) returns the starting indices of any occurrences
%	of the shorter of the two strings within the longer.
%	Example:
%	    s = 'How much wood would a woodchuck chuck?';
%	    findstr(s,'a')    returns  21
%	    findstr(s,'wood') returns  [10 23]
%	    findstr(s,'Wood') returns  []
%	    findstr(s,' ')    returns  [4 9 14 20 22 32]
%	See also STRCMP.

%	Copyright (c) 1984-93 by The MathWorks, Inc.
%	$Revision: 1.3 $  $Date: 1993/06/09 22:09:40 $

% Make s2 the shorter.
if length(s1) < length(s2)
   t = s1; s1 = s2; s2 = t;
end

% Extend s1 by something as long as s2, but which doesn't match.
s1 = [s1 0*s2];

% Repeatedly shorten an index vector which points to increasingly 
% longer matches. 
k = 1:length(s1);
for i = 1:length(s2)
   k = k(find(s1(k+i-1) == s2(i)));
end

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?