5678
|
1 ## Copyright (C) 2004 by Alois Schloegl |
|
2 ## |
|
3 ## This program is free software; you can redistribute it and/or |
|
4 ## modify it under the terms of the GNU General Public License |
|
5 ## as published by the Free Software Foundation; either version 2 |
|
6 ## of the License, or (at your option) any later version. |
|
7 ## |
|
8 ## This program is distributed in the hope that it will be useful, |
|
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 ## GNU General Public License for more details. |
|
12 ## |
|
13 ## You should have received a copy of the GNU General Public License |
|
14 ## along with this program; if not, write to the Free Software |
|
15 ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
|
16 |
|
17 ## -*- texinfo -*- |
|
18 ## @deftypefn {Function File} {@var{idx} =} strfind (@var{str}, @var{pattern}) |
|
19 ## @deftypefnx {Function File} {@var{idx} =} strfind (@var{cellstr}, @var{pattern}) |
|
20 ## Search for @var{pattern} in the string @var{str} and return the |
|
21 ## starting index of every such occurrence in the vector @var{idx}. |
|
22 ## If there is no such occurrence, or if @var{pattern} is longer |
|
23 ## than @var{str}, then @var{idx} is the empty array @code{[]}. |
|
24 ## |
|
25 ## If the cell array of strings @var{cellstr} is specified instead of the |
|
26 ## string @var{str}, then @var{idx} is a cell array of vectors, as specified |
|
27 ## above. |
|
28 ## @seealso{findstr, strmatch, strcmp, strncmp, strcmpi, strncmpi} |
|
29 ## @end deftypefn |
|
30 |
|
31 ## Author: alois schloegl <a.schloegl@ieee.org> |
|
32 ## Created: 1 November 2004 |
|
33 ## Adapted-By: William Poetra Yoga Hadisoeseno <williampoetra@gmail.com> |
|
34 |
|
35 function idx = strfind (text, pattern) |
|
36 |
|
37 if (nargin != 2) |
|
38 usage ("idx = strfind (text, pattern)"); |
|
39 elseif (! ischar (pattern)) |
|
40 error ("strfind: pattern must be a string value"); |
|
41 endif |
|
42 |
|
43 lp = length (pattern); |
|
44 |
|
45 if (ischar (text)) |
|
46 idx = __strfind_string__ (text, pattern, lp); |
|
47 elseif (iscellstr (text)) |
|
48 idx = cell (size (text)); |
|
49 for i = 1:(numel (text)) |
|
50 idx{i} = __strfind_string__ (text{i}, pattern, lp); |
|
51 endfor |
|
52 else |
|
53 error ("strfind: text must be a string or cell array of strings"); |
|
54 endif |
|
55 |
|
56 ### endfunction |
|
57 |
|
58 function idx = __strfind_string__ (text, pattern, lp) |
|
59 |
|
60 idx = 1:(length (text) - lp + 1); |
|
61 k = 0; |
|
62 while (k < lp && ! isempty (idx)) |
|
63 idx = idx(text(idx + k) == pattern(++k)); |
|
64 endwhile |
|
65 |
|
66 ### endfunction |