Published on :
Macro CREATION_INTERNE

String Manipulation with %SCAN Macro

This code is also available in: Deutsch Español Français
The code defines a macro named `name` that accepts a `fullname` parameter. Inside the macro, the `%SCAN` macro function is used to extract different parts of the name. The second word (assumed to be the first name) is extracted first, followed by the first word (assumed to be the last name), using the comma as an implicit default delimiter (or the second delimiter if the comma is explicitly in %SCAN's default delimiter list if not masked). The extracted parts are then concatenated in 'first name last name' order into a new macro variable `newname`, which is then displayed in the SAS© log via `%PUT`. The macro call uses the `%str` function to mask the comma present in the string 'O'Malley, George', ensuring that the string is treated as a single argument by the macro.
Data Analysis

Type : CREATION_INTERNE


The source code does not manipulate data from SAS tables or external files. It operates solely on a literal character string passed as an argument to a macro. Therefore, there are no dependencies on SASHELP data or unmanaged external data.

1 Code Block
MACRO DEFINITION
Explanation :
This block defines the `name` macro. It takes a `fullname` argument. Inside, it uses `%SCAN` to extract the second and first parts of the `fullname` string (corresponding respectively to the first name and last name if the format is 'Last Name, First Name'). Then, it assembles these parts in 'first name last name' order and stores the result in the `newname` macro variable. Finally, the value of `newname` is written to the SAS log.
Copied!
1%macro name(fullname);
2 %let first=%scan(&fullname,2);
3 %let last=%scan(&fullname,1);
4 %let newname=&first &last;
5 %put &newname;
6%mend name;
2 Code Block
MACRO CALL
Explanation :
This block calls the previously defined `name` macro. The string 'O'Malley, George' is passed as the `fullname` argument. The use of `%str()` is crucial here to mask the comma and apostrophe, so they are treated as literal characters of the string rather than as macro parameter delimiters or special characters by the SAS macro preprocessor. The result displayed in the log will be 'George O'Malley'.
Copied!
1%name(%str(O%'Malley, George))
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.