🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Calcite | Level 5

## 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?

-iwin

1 ACCEPTED SOLUTION

Accepted Solutions
Super User

## 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));

3 REPLIES 3
Super User

## 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));

Fluorite | Level 6

## 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.

Calcite | Level 5

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

Thanks a lot for the fast responses.

They have been very helpful.

Discussion stats
• 3 replies
• 1050 views
• 2 likes
• 3 in conversation