Remove Last Character from String in SAS

In SAS, the substr() function can be used to remove the last character from a string. The substr() function takes three arguments: the name of the source string, the starting position of the desired substring, and the length of the desired substring. To remove the last character, the length argument can be set to the length of the source string minus one. This will return a substring without the last character of the source string.


The easiest way to remove the last character from a string in SAS is to use the 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.

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

x