NCCOOS Trac Projects: Top | Web | Platforms | Processing | Viz | Sprints | Sandbox | (Wind)

root/gliderproc/trunk/MATLAB/strfun/substr.m

Revision 495 (checked in by cbc, 11 years ago)

Initial import of Stark code.

Line 
1 function outstr = substr( str, offset, len )
2 %SUBSTR Extract a substring out of a string.
3 %
4 %   SUBSTR( STRING, OFFSET, LENGTH ) extracts a substring out of STRING
5 %   with given LENGTH starting at the given OFFSET.  First character is
6 %   at offset 0.  If OFFSET is negative, starts that far from the end of
7 %   the string.  If LENGTH is omitted, returns everything to the end of
8 %   the string.  If LENGTH is negative, removes that many characters
9 %   from the end of the string.
10 %
11 %   Examples:
12 %
13 %      Get first character:              substr( string,  0, 1 )
14 %      Get last character:               substr( string, -1, 1 )
15 %      Remove first character:           substr( string,  1 )
16 %      Remove last character:            substr( string,  0, -1 )
17 %      Remove first and last character:  substr( string,  1, -1 )
18 %
19 %   SUBSTR is a Matlab version of the Perl operator with the same name.
20 %   However, unlike Perl's SUBSTR, no warning is produced if the
21 %   substring is totally outside the string.
22 %
23 % Calls: none
24
25 %   Author:      Peter J. Acklam
26 %   Time-stamp:  2000-02-29 01:38:52
27 %   E-mail:      jacklam@math.uio.no
28 %   WWW URL:     http://www.math.uio.no/~jacklam
29
30    % Check number of input arguments.
31    error( nargchk( 2, 3, nargin ) );
32
33    n = length(str);
34
35    % Get lower index.
36    lb = offset+1;               % From beginning of string.
37    if offset < 0
38       lb = lb+n;                % From end of string.
39    end
40    lb = max( lb, 1 );
41
42    % Get upper index
43    if nargin == 2               % SUBSTR( STR, OFFSET )
44       ub = n;
45    elseif nargin == 3           % SUBSTR( STR, OFFSET, LEN )
46       if len < 0
47          ub = n+len;
48       else
49          ub = lb+len-1;
50       end
51       ub = min( ub, n );
52    end
53
54    % Extract substring.
55    outstr = str( lb : ub );
Note: See TracBrowser for help on using the browser.