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