Taking Substrings - SAS Programming

The SUBSTR function is the first of the various character functions we demonstrate.A brief review is in order. A "string" in computer parlance is a collection of characters that are assigned to a variable.For example,a character variable called ID could have a value of 427NJ or 12345. Notice that a character string may consist solely of numerals as long as it has been declared as a character variable to the program. Suppose you have ID's of length 5,and the last two characters represent a state code (such as 427NJ above).Data set OLD,following, contains some sample ID's:

Data Set OLD
ID
427NJ
125NY

Here is a program to extract the state code from the ID:

Example

DATA NEW;
SET OLD; *OLD CONTAINS ID;
LENGTH STATE $ 2;
STATE=SUBSTR (ID,4,2);
RON;

The values for STATE are N J and NY in this example.

The general form of the substring function is:

SUBSTR (char_variable,starting_position, length);

The char_yariable can also be a character expression or a character constant.It is a good idea to use a LENGTH statement to assign a length to the substring variable as is done here.The dollar sign in the LENGTH statement indicates that STATE is a character variable and the 2 indicates its length.If you don't take the trouble to do this,the length of the substring is the same as the length of the variable from which you are extracting the substring.This is both wasteful and potentially dangerous in that it can lead to erroneous results.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

SAS Programming Topics