annotate toolboxes/bioakustik_tools/strings/substr.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
rev   line source
wolffd@0 1 function outstr = substr(str, offset, len, repl)
wolffd@0 2 %SUBSTR Extract a substring out of a string.
wolffd@0 3 %
wolffd@0 4 % SUBSTR(STRING, OFFSET, LENGTH) extracts a substring out of STRING with
wolffd@0 5 % given LENGTH starting at the given OFFSET. First character is at offset 0.
wolffd@0 6 % If OFFSET is negative, starts that far from the end of the string. If
wolffd@0 7 % LENGTH is omitted, returns everything to the end of the string. If LENGTH
wolffd@0 8 % is negative, removes that many characters from the end of the string.
wolffd@0 9 %
wolffd@0 10 % SUBSTR(STRING, OFFSET, LENGTH, REPLACEMENT) will not return the substring
wolffd@0 11 % as specified by STRING, OFFSET, and LENGTH (see above) but rather replace
wolffd@0 12 % it by REPLACEMENT and return the result.
wolffd@0 13 %
wolffd@0 14 % Examples:
wolffd@0 15 %
wolffd@0 16 % Get first character: substr(string, 0, 1)
wolffd@0 17 % Get last character: substr(string, -1, 1)
wolffd@0 18 % Remove first character: substr(string, 1)
wolffd@0 19 % Remove last character: substr(string, 0, -1)
wolffd@0 20 % Remove first and last character: substr(string, 1, -1)
wolffd@0 21 %
wolffd@0 22 % SUBSTR is a MATLAB version of the Perl operator with the same name.
wolffd@0 23 % However, unlike Perl's SUBSTR, no warning is produced if the substring is
wolffd@0 24 % totally outside the string.
wolffd@0 25
wolffd@0 26 % Author: Peter J. Acklam
wolffd@0 27 % Time-stamp: 2004-02-21 22:49:14 +0100
wolffd@0 28 % E-mail: pjacklam@online.no
wolffd@0 29 % URL: http://home.online.no/~pjacklam
wolffd@0 30
wolffd@0 31 % Check number of input arguments.
wolffd@0 32 error(nargchk(2, 4, nargin));
wolffd@0 33
wolffd@0 34 n = length(str);
wolffd@0 35
wolffd@0 36 % Get lower index.
wolffd@0 37 lb = offset + 1; % offset from beginning of string
wolffd@0 38 if offset < 0
wolffd@0 39 lb = lb + n; % offset from end of string
wolffd@0 40 end
wolffd@0 41 lb = max(lb, 1);
wolffd@0 42
wolffd@0 43 % Get upper index.
wolffd@0 44 if nargin == 2 % SUBSTR(STR, OFFSET)
wolffd@0 45 ub = n;
wolffd@0 46 elseif nargin > 2 % SUBSTR(STR, OFFSET, LEN)
wolffd@0 47 if len >= 0
wolffd@0 48 ub = lb + len - 1;
wolffd@0 49 else
wolffd@0 50 ub = n + len;
wolffd@0 51 end
wolffd@0 52 ub = min(ub, n);
wolffd@0 53 end
wolffd@0 54
wolffd@0 55 % Extract or replace substring.
wolffd@0 56 if nargin < 4
wolffd@0 57 outstr = str(lb : ub); % extract substring
wolffd@0 58 else
wolffd@0 59 outstr = [str(1:lb-1) repl str(ub+1:end)]; % replace substring
wolffd@0 60 end