1 ## Copyright (C) 2009-2012 Jaroslav Hajek
3 ## This file is part of Octave.
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 3 of the License, or (at
8 ## your option) any later version.
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.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {[@var{cstr}] =} strsplit (@var{s}, @var{sep})
21 ## @deftypefnx {Function File} {[@var{cstr}] =} strsplit (@var{s}, @var{sep}, @var{strip_empty})
22 ## Split the string @var{s} using one or more separators @var{sep} and return
23 ## a cell array of strings. Consecutive separators and separators at
24 ## boundaries result in empty strings, unless @var{strip_empty} is true.
25 ## The default value of @var{strip_empty} is false.
27 ## 2-D character arrays are split at separators and at the original column
34 ## strsplit ("a,b,c", ",")
42 ## strsplit (["a,b" ; "cde"], ",")
54 function cstr = strsplit (s, sep, strip_empty = false)
56 if (nargin < 2 || nargin > 3)
58 elseif (! ischar (s) || ! ischar (sep))
59 error ("strsplit: S and SEP must be string values");
60 elseif (! isscalar (strip_empty))
61 error ("strsplit: STRIP_EMPTY must be a scalar value");
65 cstr = cell (size (s));
68 ## For 2-D arrays, add separator character at line boundaries
69 ## and transform to single string
71 s = reshape (s.', 1, numel (s));
75 ## Split s according to delimiter
78 idx = find (s == sep);
80 ## Multiple separators
81 idx = strchr (s, sep);
84 ## Get substring lengths.
88 strlens = [idx(1)-1, diff(idx)-1, numel(s)-idx(end)];
94 strlens = strlens(strlens != 0);
98 cstr = mat2cell (s, 1, strlens);
104 %!assert (strsplit ("road to hell", " "), {"road", "to", "hell"})
105 %!assert (strsplit ("road to^hell", " ^"), {"road", "to", "hell"})
106 %!assert (strsplit ("road to--hell", " -", true), {"road", "to", "hell"})
107 %!assert (strsplit (["a,bc";",de"], ","), {"a", "bc", ones(1,0), "de "})
108 %!assert (strsplit (["a,bc";",de"], ",", true), {"a", "bc", "de "})
109 %!assert (strsplit (["a,bc";",de"], ", ", true), {"a", "bc", "de"})
111 %% Test input validation
113 %!error strsplit ("abc")
114 %!error strsplit ("abc", "b", true, 4)
115 %!error <S and SEP must be string values> strsplit (123, "b")
116 %!error <S and SEP must be string values> strsplit ("abc", 1)
117 %!error <STRIP_EMPTY must be a scalar value> strsplit ("abc", "def", ones(3,3))