changelog shortlog tags changeset files revisions annotate raw

scripts/strings/substr.m

changeset 10289: 4b124317dc38
parent:eb63fbe60fab
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (61 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 1996, 1999, 2000, 2004, 2005, 2006, 2007, 2008,
2## 2009 Kurt Hornik
3##
4## This file is part of Octave.
5##
6## Octave is free software; you can redistribute it and/or modify it
7## under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 3 of the License, or (at
9## your option) any later version.
10##
11## Octave is distributed in the hope that it will be useful, but
12## WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14## General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with Octave; see the file COPYING. If not, see
18## <http://www.gnu.org/licenses/>.
19
20## -*- texinfo -*-
21## @deftypefn {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.
24##
25## If @var{offset} is negative, extraction starts that far from the end of
26## the string. If @var{len} is omitted, the substring extends to the end
27## of S.
28##
29## For example,
30##
31## @example
32## @group
33## substr ("This is a test string", 6, 9)
34## @result{} "is a test"
35## @end group
36## @end example
37##
38## This function is patterned after AWK. You can get the same result by
39## @code{@var{s}(@var{offset} : (@var{offset} + @var{len} - 1))}.
40## @end deftypefn
41
42## Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
43## Adapted-By: jwe
44
45function t = substr (s, offset, len)
46
47 if (nargin < 2 || nargin > 3)
48 print_usage ();
49 endif
50
51 if (ischar (s))
52 nc = columns (s);
53 if (abs (offset) > 0 && abs (offset) <= nc)
54 if (offset <= 0)
55 offset += nc + 1;
56 endif
57 if (nargin == 2)
58 eos = nc;
59 else
60 eos = offset + len - 1;
61 endif
62 if (eos <= nc)
63 t = s (:, offset:eos);
64 else
65 error ("substr: length = %d out of range", len);
66 endif
67 else
68 error ("substr: offset = %d out of range", offset);
69 endif
70 else
71 error ("substr: expecting string argument");
72 endif
73
74endfunction
75
76%!assert(strcmp (substr ("This is a test string", 6, 9), "is a test"));
77
78%!error substr ();
79
80%!error substr ("foo", 2, 3, 4);
81