2303
|
1 ### Copyright (C) 1996 Kurt Hornik |
|
2 ### |
|
3 ### This file is part of Octave. |
|
4 ### |
|
5 ### Octave is free software; you can redistribute it and/or modify it |
|
6 ### under the terms of the GNU General Public License as published by |
|
7 ### the Free Software Foundation; either version 2, or (at your option) |
|
8 ### any later version. |
|
9 ### |
|
10 ### Octave is distributed in the hope that it will be useful, but |
|
11 ### WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ### General Public License for more details. |
|
14 ### |
|
15 ### You should have received a copy of the GNU General Public License |
|
16 ### along with Octave; see the file COPYING. If not, write to the Free |
|
17 ### Software Foundation, 59 Temple Place - Suite 330, Boston, MA |
|
18 ### 02111-1307, USA. |
2272
|
19 |
2311
|
20 ## usage: findstr (s, t [, overlap]) |
|
21 ## |
|
22 ## Returns the vector of all positions in the longer of the two strings |
|
23 ## S and T where an occurence of the shorter of the two starts. |
|
24 ## |
|
25 ## If the optional argument OVERLAP is nonzero, the returned vector |
|
26 ## can include overlapping positions (this is the default). |
|
27 ## |
|
28 ## For example, |
|
29 ## |
|
30 ## findstr ("abababa", "aba") => [1, 3, 5] |
|
31 ## findstr ("abababa", "aba", 0) => [1, 5] |
2272
|
32 |
2311
|
33 function v = findstr (s, t, overlap) |
2275
|
34 |
2303
|
35 ## Original version by Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>. |
2272
|
36 |
2275
|
37 if (nargin < 2 || nargin > 3) |
|
38 usage ("findstr (s, t [, overlap])"); |
|
39 endif |
|
40 |
|
41 if (nargin == 2) |
|
42 overlap = 1; |
2272
|
43 endif |
|
44 |
|
45 if (isstr (s) && isstr (t)) |
|
46 |
2303
|
47 ## Make S be the longer string. |
2272
|
48 |
|
49 if (length (s) < length (t)) |
|
50 tmp = s; |
|
51 s = t; |
|
52 t = tmp; |
|
53 endif |
|
54 |
|
55 s = toascii (s); |
|
56 t = toascii (t); |
|
57 |
2275
|
58 l_t = length (t); |
|
59 |
|
60 ind = 1 : l_t; |
|
61 limit = length (s) - l_t + 1; |
2272
|
62 v = zeros (1, limit); |
|
63 i = 0; |
|
64 |
2275
|
65 k = 1; |
|
66 while (k <= limit) |
2272
|
67 if (s (ind + k - 1) == t) |
|
68 v (++i) = k; |
2275
|
69 if (! overlap) |
|
70 k = k + l_t - 1; |
|
71 endif |
2272
|
72 endif |
2275
|
73 k++; |
|
74 endwhile |
2272
|
75 |
|
76 if (i > 0) |
|
77 v = v (1:i); |
|
78 else |
|
79 v = []; |
|
80 endif |
|
81 |
|
82 else |
2275
|
83 error ("findstr: expecting first two arguments to be strings"); |
2272
|
84 endif |
|
85 |
|
86 endfunction |