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