wolffd@0: function outstr = substr(str, offset, len, repl) wolffd@0: %SUBSTR Extract a substring out of a string. wolffd@0: % wolffd@0: % SUBSTR(STRING, OFFSET, LENGTH) extracts a substring out of STRING with wolffd@0: % given LENGTH starting at the given OFFSET. First character is at offset 0. wolffd@0: % If OFFSET is negative, starts that far from the end of the string. If wolffd@0: % LENGTH is omitted, returns everything to the end of the string. If LENGTH wolffd@0: % is negative, removes that many characters from the end of the string. wolffd@0: % wolffd@0: % SUBSTR(STRING, OFFSET, LENGTH, REPLACEMENT) will not return the substring wolffd@0: % as specified by STRING, OFFSET, and LENGTH (see above) but rather replace wolffd@0: % it by REPLACEMENT and return the result. wolffd@0: % wolffd@0: % Examples: wolffd@0: % wolffd@0: % Get first character: substr(string, 0, 1) wolffd@0: % Get last character: substr(string, -1, 1) wolffd@0: % Remove first character: substr(string, 1) wolffd@0: % Remove last character: substr(string, 0, -1) wolffd@0: % Remove first and last character: substr(string, 1, -1) wolffd@0: % wolffd@0: % SUBSTR is a MATLAB version of the Perl operator with the same name. wolffd@0: % However, unlike Perl's SUBSTR, no warning is produced if the substring is wolffd@0: % totally outside the string. wolffd@0: wolffd@0: % Author: Peter J. Acklam wolffd@0: % Time-stamp: 2004-02-21 22:49:14 +0100 wolffd@0: % E-mail: pjacklam@online.no wolffd@0: % URL: http://home.online.no/~pjacklam wolffd@0: wolffd@0: % Check number of input arguments. wolffd@0: error(nargchk(2, 4, nargin)); wolffd@0: wolffd@0: n = length(str); wolffd@0: wolffd@0: % Get lower index. wolffd@0: lb = offset + 1; % offset from beginning of string wolffd@0: if offset < 0 wolffd@0: lb = lb + n; % offset from end of string wolffd@0: end wolffd@0: lb = max(lb, 1); wolffd@0: wolffd@0: % Get upper index. wolffd@0: if nargin == 2 % SUBSTR(STR, OFFSET) wolffd@0: ub = n; wolffd@0: elseif nargin > 2 % SUBSTR(STR, OFFSET, LEN) wolffd@0: if len >= 0 wolffd@0: ub = lb + len - 1; wolffd@0: else wolffd@0: ub = n + len; wolffd@0: end wolffd@0: ub = min(ub, n); wolffd@0: end wolffd@0: wolffd@0: % Extract or replace substring. wolffd@0: if nargin < 4 wolffd@0: outstr = str(lb : ub); % extract substring wolffd@0: else wolffd@0: outstr = [str(1:lb-1) repl str(ub+1:end)]; % replace substring wolffd@0: end