DATA Step, Macro, Functions and more

LENGTH Statement causes INDEX Function to return an incorrect result

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

LENGTH Statement causes INDEX Function to return an incorrect result

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


Accepted Solutions
Solution
‎08-15-2013 06:23 PM
Super User
Posts: 10,500

Re: LENGTH Statement causes INDEX Function to return an incorrect result

Many character operations pad variables to the max length, which appears to be the case here.

Use

x=index(a, strip(b));

View solution in original post


All Replies
Solution
‎08-15-2013 06:23 PM
Super User
Posts: 10,500

Re: LENGTH Statement causes INDEX Function to return an incorrect result

Many character operations pad variables to the max length, which appears to be the case here.

Use

x=index(a, strip(b));

Frequent Contributor
Posts: 129

Re: LENGTH Statement causes INDEX Function to return an incorrect result

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.

New Contributor
Posts: 2

Re: LENGTH Statement causes INDEX Function to return an incorrect result

Thanks a lot for the fast responses.

They have been very helpful.

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 225 views
  • 0 likes
  • 3 in conversation