Monday, February 6, 2017

Hack 4.11 Removing Leading and Trailing Blanks with the STRIP Function


SAS Programming Professionals,

Did you know that there is a function that will effortlessly strip off leading and trailing blanks from a character variable?

The aptly named STRIP function allows you to do just that and is a great replacement for the old TRIM(LEFT(character-variable)) construct many programmers used to use.

Here is an example of using the STRIP function:

data cars;
set  sashelp.cars;

car_statement = "The " || strip(make) ||
                   " " || strip(model)||
              " is a " || strip(type) ||
              ".";

run;

proc print noobs data=cars;                    
      var car_statement;
run;

Which produces, in part:

The Acura MDX is a SUV.
The Acura RSX Type S 2dr is a Sedan.
The Acura TSX 4dr is a Sedan.
The Acura TL 4dr is a Sedan.
The Acura 3.5 RL 4dr is a Sedan.
The Acura 3.5 RL w/Navigation 4dr is a Sedan.
The Acura NSX coupe 2dr manual S is a Sports.
The Audi A4 1.8T 4dr is a Sedan.
The Audi A41.8T convertible 2dr is a Sedan.

In the example, we are constructing variable CAR_STATEMENT by concatenating string constants and concatenating the variables MAKE (13 characters in length), MODEL (40 characters in length) and TYPE (8 characters length).  Without the STRIP function, there would be big gaps in CAR_STATEMENT because many of the MAKEs, MODELs, and TYPEs are not 13, 40, and 8 characters long, respectively.

Best of luck in all your SAS endeavors!

---MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition:  http://tinyurl.com/z8bzx2e 
Kindle edition: http://tinyurl.com/zypgqa7 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers

No comments:

Post a Comment