2313
|
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 |
2314
|
33 ## Author: jwe |
|
34 |
2311
|
35 function v = findstr (s, t, overlap) |
2275
|
36 |
2303
|
37 ## Original version by Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>. |
2272
|
38 |
2275
|
39 if (nargin < 2 || nargin > 3) |
|
40 usage ("findstr (s, t [, overlap])"); |
|
41 endif |
|
42 |
|
43 if (nargin == 2) |
|
44 overlap = 1; |
2272
|
45 endif |
|
46 |
|
47 if (isstr (s) && isstr (t)) |
|
48 |
2303
|
49 ## Make S be the longer string. |
2272
|
50 |
|
51 if (length (s) < length (t)) |
|
52 tmp = s; |
|
53 s = t; |
|
54 t = tmp; |
|
55 endif |
|
56 |
|
57 s = toascii (s); |
|
58 t = toascii (t); |
|
59 |
2275
|
60 l_t = length (t); |
|
61 |
|
62 ind = 1 : l_t; |
|
63 limit = length (s) - l_t + 1; |
2272
|
64 v = zeros (1, limit); |
|
65 i = 0; |
|
66 |
2275
|
67 k = 1; |
|
68 while (k <= limit) |
2272
|
69 if (s (ind + k - 1) == t) |
|
70 v (++i) = k; |
2275
|
71 if (! overlap) |
|
72 k = k + l_t - 1; |
|
73 endif |
2272
|
74 endif |
2275
|
75 k++; |
|
76 endwhile |
2272
|
77 |
|
78 if (i > 0) |
|
79 v = v (1:i); |
|
80 else |
|
81 v = []; |
|
82 endif |
|
83 |
|
84 else |
2275
|
85 error ("findstr: expecting first two arguments to be strings"); |
2272
|
86 endif |
|
87 |
|
88 endfunction |