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} {} substr (@var{s}, @var{offset})
21 ## @deftypefnx {Function File} {} substr (@var{s}, @var{offset}, @var{len})
22 ## Return the substring of @var{s} which starts at character number
23 ## @var{offset} and is @var{len} characters long.
25 ## Position numbering for offsets begins with 1. If @var{offset} is negative,
26 ## extraction starts that far from the end of the string.
28 ## If @var{len} is omitted, the substring extends to the end of @var{S}. A
29 ## negative value for @var{len} extracts to within @var{len} characters of
30 ## the end of the string
36 ## substr ("This is a test string", 6, 9)
37 ## @result{} "is a test"
38 ## substr ("This is a test string", -11)
39 ## @result{} "test string"
40 ## substr ("This is a test string", -11, -7)
45 ## This function is patterned after the equivalent function in Perl.
48 ## Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
51 function t = substr (s, offset, len)
53 if (nargin < 2 || nargin > 3)
58 error ("substr: S must be a string or string array");
59 elseif (! isscalar (offset) || (nargin == 3 && ! isscalar (len)))
60 error ("substr: OFFSET and LEN must be scalar integers");
63 offset = fix (offset);
65 if (abs (offset) > nc || offset == 0)
66 error ("substr: OFFSET = %d out of range", offset);
80 eos = offset + len - 1;
85 error ("substr: length LEN = %d out of range", len);
86 elseif (offset > eos && len != 0)
87 error ("substr: No overlap with chosen values of OFFSET and LEN");
95 %!assert (substr ("This is a test string", 6, 9), "is a test");
96 %!assert (substr ("This is a test string", -11), "test string");
97 %!assert (substr ("This is a test string", -11, 4), "test");
98 %!assert (substr ("This is a test string", -11, -7), "test");
99 %!assert (substr ("This is a test string", 1, -7), "This is a test");
100 %!assert (isempty (substr ("This is a test string", 1, 0)));
102 %% Test input validation
104 %!error substr ("foo", 2, 3, 4)
105 %!error substr (ones (5, 1), 1, 1)
106 %!error substr ("foo", ones(2,2))
107 %!error substr ("foo", 1, ones(2,2))
108 %!error substr ("foo", 0)
109 %!error substr ("foo", 5)
110 %!error substr ("foo", 1, 5)
111 %!error substr ("foo", -1, 5)
112 %!error substr ("foo", 2, -5)