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

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