Production Ready Macros for SAS Application Developers
https://github.com/sasjs/core
mf_trimstr.sas
Go to the documentation of this file.
1 /**
2  @file mf_trimstr.sas
3  @brief Removes character(s) from the end, if they exist
4  @details If the designated characters exist at the end of the string, they
5  are removed
6 
7  %put %mf_trimstr(/blah/,/); * /blah;
8  %put %mf_trimstr(/blah/,h); * /blah/;
9  %put %mf_trimstr(/blah/,h/);* /bla;
10 
11  <h4> Dependencies </h4>
12 
13 
14  @param basestr The string to be modified
15  @param trimstr The string to be removed from the end of `basestr`, if it exists
16 
17  @return output returns result with the value of `trimstr` removed from the end
18 
19 
20  @version 9.2
21  @author Allan Bowe
22 
23 **/
24 
25 %macro mf_trimstr(basestr,trimstr);
26 %local baselen trimlen trimval;
27 
28 /* return if basestr is shorter than trimstr (or 0) */
29 %let baselen=%length(%superq(basestr));
30 %let trimlen=%length(%superq(trimstr));
31 %if &baselen < &trimlen or &baselen=0 %then %return;
32 
33 /* obtain the characters from the end of basestr */
34 %let trimval=%qsubstr(%superq(basestr)
35  ,%length(%superq(basestr))-&trimlen+1
36  ,&trimlen);
37 
38 /* compare and if matching, chop it off! */
39 %if %superq(basestr)=%superq(trimstr) %then %do;
40  %return;
41 %end;
42 %else %if %superq(trimval)=%superq(trimstr) %then %do;
43  %qsubstr(%superq(basestr),1,%length(%superq(basestr))-&trimlen)
44 %end;
45 %else %do;
46  &basestr
47 %end;
48 
49 %mend;