SAS: How to Remove First Character from String

SAS provides a function called substr() which can be used to remove the first character from a string. The substr() function accepts three arguments: the original string, the start position from which to begin extraction, and the number of characters to extract. To remove the first character, the start position is set to 2 and the number of characters to extract is set to the length of the original string minus one. This will result in a new string with the first character removed.


The easiest way to remove the first 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, 2);
run;

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

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

Example: Remove First 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;
xMavs 113
xPacers 95
xCavs 120
xLakers 114
xHeat 123
xKings 119
xRaptors 105
xHawks 95
xMagic 103
xSpurs 119
;
run;

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

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

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

/*create new dataset where first character in each string of team column is removed*/
data new_data;
    set my_data;
    team = substr(team, 2);
run;

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

Notice that the first 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, 2) and not specifying a value for the last argument of N, we’re able to extract the substring from the string in the team column starting from the second character to the last character.

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

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

x