comparison scripts/strings/split.m @ 5462:74804828df1a

[project @ 2005-09-22 18:36:22 by jwe]
author jwe
date Thu, 22 Sep 2005 18:36:23 +0000
parents ec8c33dcd1bf
children 3e4564ddd985
comparison
equal deleted inserted replaced
5461:8d8fc8eff9e6 5462:74804828df1a
16 ## along with Octave; see the file COPYING. If not, write to the Free 16 ## along with Octave; see the file COPYING. If not, write to the Free
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 ## 02110-1301, USA. 18 ## 02110-1301, USA.
19 19
20 ## -*- texinfo -*- 20 ## -*- texinfo -*-
21 ## @deftypefn {Function File} {} split (@var{s}, @var{t}) 21 ## @deftypefn {Function File} {} split (@var{s}, @var{t}, @var{n})
22 ## Divides the string @var{s} into pieces separated by @var{t}, returning 22 ## Divides the string @var{s} into pieces separated by @var{t}, returning
23 ## the result in a string array (padded with blanks to form a valid 23 ## the result in a string array (padded with blanks to form a valid
24 ## matrix). For example, 24 ## matrix). If the optional input @var{n} is supplied, split @var{s}
25 ## into at most @var{n} different pieces.
26 ##
27 ## For example,
25 ## 28 ##
26 ## @example 29 ## @example
27 ## split ("Test string", "t") 30 ## split ("Test string", "t")
28 ## @result{} "Tes " 31 ## @result{} "Tes "
29 ## " s " 32 ## " s "
30 ## "ring" 33 ## "ring"
31 ## @end example 34 ## @end example
35 ##
36 ## @example
37 ## split ("Test string", "t", 2)
38 ## @result{} "Tes "
39 ## " string"
40 ## @end example
32 ## @end deftypefn 41 ## @end deftypefn
33 42
34 ## Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at> 43 ## Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
35 ## Adapted-By: jwe 44 ## Adapted-By: jwe
36 45
37 function m = split (s, t) 46 function m = split (s, t, n)
38 47
39 if (nargin == 2) 48 if (nargin == 2 || nargin == 3)
49 if (nargin == 2)
50 n = length (s);
51 endif
52
40 if (ischar (s) && ischar (t)) 53 if (ischar (s) && ischar (t))
41 54
42 l_s = length (s); 55 l_s = length (s);
43 l_t = length (t); 56 l_t = length (t);
44 57
58 71
59 ind = findstr (s, t, 0); 72 ind = findstr (s, t, 0);
60 if (length (ind) == 0) 73 if (length (ind) == 0)
61 m = s; 74 m = s;
62 return; 75 return;
76 elseif (n - 1 < length(ind))
77 ind = ind(1:n-1)
63 endif 78 endif
64 ind2 = [1, ind+l_t]; 79 ind2 = [1, ind+l_t];
65 ind = [ind, l_s+1]; 80 ind = [ind, l_s+1];
66 81
67 ind_diff = ind-ind2; 82 ind_diff = ind-ind2;
78 endfor 93 endfor
79 else 94 else
80 error ("split: both s and t must be strings"); 95 error ("split: both s and t must be strings");
81 endif 96 endif
82 else 97 else
83 usage ("split (s, t)"); 98 usage ("split (s, t, n)");
84 endif 99 endif
85 100
86 endfunction 101 endfunction