1 ## Copyright (C) 1996-2012 Kurt Hornik
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} {} strtrim (@var{s})
21 ## Remove leading and trailing whitespace from @var{s}. If
22 ## @var{s} is a matrix, @var{strtrim} trims each row to the length of
23 ## longest string. If @var{s} is a cell array of strings, operate recursively
24 ## on each string element. For example:
31 ## strtrim ([" abc "; " def "])
32 ## @result{} ["abc " ; " def"]
38 ## Author: John Swensen <jpswensen@jhu.edu>
40 ## This function was derived from deblank.
42 function s = strtrim (s)
50 k = find (! isspace (s));
51 if (isempty (s) || isempty (k))
54 s = s(:, ceil (min (k) / rows (s)):ceil (max (k) / rows (s)));
59 char_idx = cellfun ("isclass", s, "char");
60 cell_idx = cellfun ("isclass", s, "cell");
61 if (! all (char_idx | cell_idx))
62 error ("strtrim: S argument must be a string or cellstring");
65 ## Divide work load. Recursive cellfun strtrim call is slow
66 ## and avoided where possible.
67 s(char_idx) = regexprep (s(char_idx), "^[\\s\v]+|[\\s\v]+$", '');
68 s(cell_idx) = cellfun ("strtrim", s(cell_idx), "UniformOutput", false);
71 error ("strtrim: S argument must be a string or cellstring");
77 %!assert (strtrim (" abc "), "abc");
78 %!assert (strtrim (" "), "");
79 %!assert (strtrim ("abc"), "abc");
80 %!assert (strtrim ([" abc "; " def "]), ["abc "; " def"]);
81 %!assert (strtrim ({" abc "; " def "}), {"abc"; "def"});
82 %!assert (strtrim ({" abc ", {" def "}}), {"abc", {"def"}});
84 %!error <Invalid call to strtrim> strtrim ();
85 %!error <Invalid call to strtrim> strtrim ("abc", "def");
86 %!error <argument must be a string> strtrim (1);
87 %!error <argument must be a string> strtrim ({[]});