To remove all leading and trailing blanks from a string variable in a SAS data step, we can use the SAS strip() function.

data k;
    a = '           this is a string with some leading and trailing blanks            ';
    b = "*" || trim(a) || "*";
    put b=;
run;

/* Output: */
b=*this is a string with some leading and trailing blanks*

When working with datasets which contain string and character variables, removing unwanted blank spaces can save space as well as ensure the data is displayed as desired in our reports.

The SAS strip() function removes leading trailing blank spaces from our string variables.

You can see how to use the SAS strip () function in a data step to remove blank spaces before the first and after the last character in the following SAS code.

data k;
    a = '      this is a string with some leading and trailing blanks            ';
    b = "*" || strip(a) || "*";
    put b=;
run;

/* Output: */
b=*this is a string with some leading and trailing blanks*

The Difference between trim(), compress(), and strip() in SAS

When working with string variables in SAS, there are a few useful functions for cleaning up whitespace and removing blanks.

In addition to the SAS strip() function, two other functions are the SAS compress() and SAS trim() functions.

The SAS compress() function gives us the ability to remove all blank spaces from a string, and the SAS trim() function removes trailing blank spaces from a string.

You can see below how each of these string manipulation functions work in the following SAS code:

data k;
    a = '     abc de fghi jkl         mnop     ';
    trim =  "*" || trim(a) || "*";
    comp =  "*" || compress(a) || "*";
    strip =  "*" || strip(a) || "*";
    put trim=;
    put comp=;
    put strip=;
run;

/* Output: */
trim=*     abc de fghi jkl         mnop*
comp=*abcdefghijklmnop*
strip=*abc de fghi jkl         mnop*

Hopefully this article has been beneficial for you to understand how to use the SAS strip() function to remove all leading and trailing blanks from a string variable in a SAS data step.

Categorized in:

SAS,

Last Update: March 20, 2024