Hi,
The normal substr function is straight forward. For example , substr(var,2,6) means substract from the 2nd place to the 6th place of var. Today I saw someone write a length function nested in substr function, do any of you know what does it mean? Substract from which place to which place?
SUBSTR(VAR,LENGTH(VAR)-4,5)
Thank you,
Runrunbunny
Hi:
It's always useful to review the syntax of the SUBSTR function when used for extraction:
Based on understanding what the 3 arguments here represent, then you can write a little test program to validate that you get the same response. Let's look at a LONG text string of 28 characters:
If I want to extract (for whatever silly reason, the characters starting in position 24 of the string (in this case, "uppet", then I would need this:
newvar = substr(var,24,5);
I can also write a test program and use PUTLOG to verify that SUBSTR is working as designed:
With a longer string, I'd have to adjust my amount to subtract or if I wanted to get a different piece from the longer string (such as the word Muppet or the word Kermit).
Cynthia
Hi Cynthia,
Thank you for taking time in doing the testing and a great example!
Like this example: SUBSTR(VAR,LENGTH(VAR)-4,5). If the length of var is 6, does the length of the 2nd argumentation is 2?
Runrunbunny
No. The third argument is the number of bytes you want to extract, NOT the position of the last character.
So
SUBSTR(VAR,2,6)
means from the 2nd through the 7th position. To get the 2nd through the 6th position would be a length of 5 not 6.
Hi Tom,
Thank you for correcting me!
Like this example: SUBSTR(VAR,LENGTH(VAR)-4,5). If the length of var is 6, does the length of the 2nd argumentation is 2?
Runrunbunny
If you want the end of the string then do not include the last argument.
If you wanted the last one character you would use
substr(x,length(x))
So if you want the last N characters you would use
substr(x,length(x)-(N-1))
Note that if the length of X is less than N then you need to use SUBSTRN() instead of SUBSTR() or you will get an error when giving it a negative starting position.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.