options nodate nostimer ls=78 ps=60; data _null_; length a b $14; a='ABC.DEF (X=Y)'; b='X=Y'; q=index(a,b); w=index(a,trim(b)); put q= w=; run;
I dont understand the answer, why is q=0 and w=10?
@HeatherNewton - If the answers fix your problem, it's good practice to update the post as answered 🙂.
Always keep in mind that character variables are padded to their defined length with blanks, and in the first call of INDEX, those blanks are there in variable b and would need to also be present in a (which they are not, of course).
In the second call to INDEX, the TRIM function removes the trailing blanks, and the remaining string is found.
This is Example 2 from the Index Function Documentation.
data _null_;
length a b $14;
a='ABC.DEF (X=Y)';
b='X=Y';
q=index(a, b);
w=index(a, trim(b));
put q= w=;
run;
What you want to notice here is the Length Statement, giving both a and b a length of $14. Meaning that SAS pads both a and b with trailing blanks. The code below gives the same as above without the Length Statement.
data _null_;
a='ABC.DEF (X=Y) ';
b='X=Y ';
q=index(a, b);
w=index(a, trim(b));
put q= w=;
run;
This means that in index(a, b) looks for the string 'X=Y ' (including trailing blanks) in the string 'ABC.DEF (X=Y) '. This returns zero because it's not there. Index(a, trim(b)) looks for 'X=Y' (without trailing blanks) in the same string. This returns 10.
Variable B has length 14. It has the value X=Y plus 11 blanks. This string of X=Y followed by 11 blanks does not appear in A.
When you do the TRIM then the value is X=Y without any trailing blanks, which does appear in A.
To fix this use
length a $14;
or even remove the LENGTH statement entirely as it is not needed in this data set.
The secret is hidden in the length statement.
Because this length statement defines b with a length of $14 the index() function will use the fully expanded value as below (blanks are also just characters):
Because this is not a match the index() function returns a value of zero.
If you use the trim function then the index() function will see the following (trailing blanks removed):
Now it's a match and that's why the index() function returns a value of 10.
Does that explain it to you?
@HeatherNewton - If the answers fix your problem, it's good practice to update the post as answered 🙂.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.