SAS: How to Remove Last Character from String


The easiest way to remove the last character from a string in SAS is to use the SUBSTR function.

You can use the following basic syntax to do so:

data new_data;
    set original_data;
    string_var = substr(string_var, 1, length(string_var)-1);
run;

This syntax extracts the substring starting from the first character to the second to last character of the string, which has the effect of removing the last character from the string.

The following example shows how to use this syntax in practice.

Example: Remove Last Character from String in SAS

Suppose we have the following dataset in SAS that contains information about various basketball teams:

/*create dataset*/
data my_data;
    input team $ points;
    datalines;
Mavsx 113
Pacersx 95
Cavsx 120
Lakersx 114
Heatx 123
Kingsx 119
Raptorsx 105
Hawksx 95
Magicx 103
Spursx 119
;
run;

/*view dataset*/
proc print data=my_data;

Notice that each string in the team column contains an x as the last character.

We can use the SUBSTR function to remove this last character from each string in the team column:

/*create new dataset where last character in each string of team column is removed*/
data new_data;
    set my_data;
    team = substr(string_var, 1, length(string_var)-1);
run;

/*view new dataset*/
proc print data=new_data;

Notice that the last character of each string in the team column has been removed.

Note that the SUBSTR function uses the following basic syntax:

SUBSTR(Source, Position, N)

where:

  • Source: The string to analyze
  • Position: The starting position to read
  • N: The number of characters to read

By using substr(team, 1, length(team)-1) we’re able to extract the substring from each string in the team column starting from the first character to the second to last character.

This has the effect of removing the last character from the string.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Extract Numbers from String in SAS
How to Use the SUBSTR Function in SAS
How to Remove Special Characters from Strings in SAS

Leave a Reply

Your email address will not be published. Required fields are marked *