Hi,
This seems like something that must have been dealt with before, but I can't find any information related with the problem.
Taking the example from the SAS Language Dictionary to illustrate the use of the INDEX Function, if I run the following code, everything goes fine: the value of x is set to 10.
data _null_;
a='ABC.DEF (X=Y)';
b='X=Y';
x=index(a,b);
put x;
run;
However, if I add as the very first statement a LENGTH statement for the variable b, assigning it a declared length of 4 (or higher), then running this code returns a value of 0 for x:
data _null_;
length b $ 4;
a='ABC.DEF (X=Y)';
b='X=Y';
x=index(a,b);
put x;
run;
Can anyone explain me why this happens, and how I can search for b in a if the declared length of b exceeds its actual length?
Thanks in advance,
-iwin
Many character operations pad variables to the max length, which appears to be the case here.
Use
x=index(a, strip(b));
Many character operations pad variables to the max length, which appears to be the case here.
Use
x=index(a, strip(b));
index function apparently does not trim trailing blanks from the value of a variable used as a parameter. That behavior is probably what should be expected.
In your first step, the data compiletr creates b with a length of 3 and there are no blanks assigned in it; so index works as expected.
When you define a length of 4 or more to b, the value used in index is right padded with blanks. So when length = 5, the string 'X=Y ' is what the index function sees.
You can test this by adding an explicit blank in your first case. Index will not find the string. Or by using compress or trim functions on b within the index function in the second example.
Thanks a lot for the fast responses.
They have been very helpful.
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.