Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SAS string


May 26, 2021 SAS


Table of contents


Strings in SAS are values enclosed in a pair of single quotes. S tring variables are also declared by adding a space and $sign at the end of the variable declaration. S AS has many powerful features to analyze and manipulate strings.

Declares a string variable

We can declare string variables and their values, as shown below. I n the following code, we declare two character variables with lengths of 6 and 5. T he LENGTH keyword is used to declare variables without creating multiple observations.

data string_examples;
   LENGTH string1 $ 6 String2 $ 5;
   /*String variables of length 6 and 5 */
   String1 = 'Hello';
   String2 = 'World';
   Joined_strings =  String1 ||String2 ;
 run;
proc print data = string_examples noobs;
run;

Run the code above and we get the output that shows the variable name and its value.

SAS string

String function

Here are some examples of SAS functions that are often used.

SUBSTRN

This function uses the start and end locations to extract substrings. I f no end position is mentioned, it extracts all characters until the end of the string.

Syntactic

SUBSTRN('stringval',p1,p2)

The following is a description of the parameters used:

  • Stringval is the value of a string variable.
  • p1 is the starting position for the extraction.
  • p2 is the number of characters extracted.

Cases

data string_examples;
   LENGTH string1 $ 6 ;
   String1 = 'Hello';
   sub_string1 = substrn(String1,2,4) ;
   /*Extract from position 2 to 4 */
   sub_string2 = substrn(String1,3) ;
   /*Extract from position 3 onwards */
run;
proc print data = string_examples noobs;
run;

In running the above code, we get the output that shows the results of the substrn function.

SAS string

TRIMN

This function removes the tail space from the string.

Syntactic

TRIMN('stringval')

The following is a description of the parameters used:

  • Stringval is the value of a string variable.
data string_examples;
   LENGTH string1 $ 7  ;
   String1='Hello  ';
   length_string1 = lengthc(String1);
   length_trimmed_string = lengthc(TRIMN(String1));
run;
proc print data = string_examples noobs;
run;

Run the code above and we get the output that shows the results of the TRIMN function.

SAS string