May 26, 2021 SAS
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.
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.
Here are some examples of SAS functions that are often used.
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.
SUBSTRN('stringval',p1,p2)
The following is a description of the parameters used:
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.
This function removes the tail space from the string.
TRIMN('stringval')
The following is a description of the parameters used:
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.