1 ## Copyright (C) 2006-2012 William Poetra Yoga Hadisoeseno
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} {} strtrunc (@var{s}, @var{n})
21 ## Truncate the character string @var{s} to length @var{n}. If @var{s}
22 ## is a character matrix, then the number of columns is adjusted.
23 ## If @var{s} is a cell array of strings, then the operation is performed
24 ## on each cell element and the new cell array is returned.
27 function s = strtrunc (s, n)
34 if (! isscalar (n) || n < 0)
35 error ("strtrunc: length N must be a positive integer (N >= 0)");
42 elseif (iscellstr (s))
43 ## Convoluted approach converts cellstr to char matrix, trims the character
44 ## matrix using indexing, and then converts back to cellstr with mat2cell.
45 ## This approach is 24X faster than using cellfun with call to strtrunc
46 idx = cellfun ("size", s, 2) > n;
47 rows = cellfun ("size", s(idx), 1);
49 s(idx) = mat2cell (char (s(idx))(:, 1:n), rows);
52 error ("strtrunc: S must be a character string or a cell array of strings");
58 %!assert (strtrunc("abcdefg", 4), "abcd");
59 %!assert (strtrunc("abcdefg", 10), "abcdefg");
60 %!assert (strtrunc(char ("abcdef", "fedcba"), 3), ["abc"; "fed"]);
61 %!assert (strtrunc({"abcdef", "fedcba"}, 3), {"abc", "fed"});
62 %!assert (strtrunc({"", "1", "21", "321"}, 1), {"", "1", "2", "3"})
63 %!assert (strtrunc({"1", "", "2"}, 1), {"1", "", "2"})
65 %! cstr = {"line1"; ["line2"; "line3"]; "line4"};
66 %! y = strtrunc (cstr, 4);
67 %! assert (size (y), [3, 1]);
68 %! assert (size (y{2}), [2, 4]);
69 %! assert (y{2}, repmat ("line", 2, 1));
71 %% Test input validation
73 %!error strtrunc ("abcd")
74 %!error strtrunc ("abcd", 4, 5)
75 %!error <N must be a positive integer> strtrunc ("abcd", ones (2,2))
76 %!error <N must be a positive integer> strtrunc ("abcd", -1)
77 %!error <S must be a character string or a cell array of strings> strtrunc (1, 1)