Removing Trailing Characters from String

This code is also available in: Deutsch Español Français
Difficulty Level
Beginner
Published on :
The `mf_trimstr` macro takes two arguments: `basestr` (the string to modify) and `trimstr` (the string to remove). It determines the length of both strings and checks if `basestr` is long enough. If `trimstr` is found at the end of `basestr`, it is removed. Otherwise, the original `basestr` is returned. The macro also handles cases where `basestr` and `trimstr` are identical, or if `basestr` is empty.
Data Analysis

Type : CREATION_INTERNE


The macro operates only on strings provided as parameters. It does not read or write external data or SAS tables. It uses macro functions for string manipulation.

1 Code Block
MACRO
Explanation :
This block defines the `mf_trimstr` macro.
1. **Local variable declaration**: `%local baselen trimlen trimval;` declares local macro variables for string lengths and the value to compare.
2. **Length check**: The lengths of `basestr` and `trimstr` are calculated. If `basestr` is shorter than `trimstr` or is empty, the macro terminates (`%return`).
3. **Substring extraction**: The macro extracts a substring from `basestr` of the same length as `trimstr`, starting from the end of `basestr`. `%superq` is used to handle special characters.
4. **Comparison and removal**:
- If `basestr` is identical to `trimstr`, the macro terminates (implicitly returns an empty string).
- If the extracted substring (`trimval`) matches `trimstr`, then `trimstr` is removed from the end of `basestr` by returning a substring of `basestr` excluding `trimstr`.
- Otherwise (no match), the original `basestr` is returned.
Copied!
1%macro mf_trimstr(basestr,trimstr);
2%local baselen trimlen trimval;
3 
4/* return if basestr is shorter than trimstr (or 0) */
5%let baselen=%LENGTH(%superq(basestr));
6%let trimlen=%LENGTH(%superq(trimstr));
7%IF &baselen < &trimlen or &baselen=0 %THEN %return;
8 
9/* obtain the characters from the end of basestr */
10%let trimval=%qsubstr(%superq(basestr)
11 ,%LENGTH(%superq(basestr))-&trimlen+1
12 ,&trimlen);
13 
14/* compare and if matching, chop it off! */
15%IF %superq(basestr)=%superq(trimstr) %THEN %DO;
16 %return;
17%END;
18%ELSE %IF %superq(trimval)=%superq(trimstr) %THEN %DO;
19 %qsubstr(%superq(basestr),1,%LENGTH(%superq(basestr))-&trimlen)
20%END;
21%ELSE %DO;
22 &basestr
23%END;
24 
25%mend mf_trimstr;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.

Related Documentation

Aucune documentation spécifique pour cette catégorie.