BookmarkSubscribeRSS Feed
shahsn11
Fluorite | Level 6

Hi Pals,

 

Below is a peice of code i am trying to understand Index function. according to me both are almost same code and should return the same result, but that is not the case. Could anybody help me understand the working of the code. 

 

data _null_;
   length a b $14;
   a='ABC.DEF (X=Y)';
   b='X=Y';
   q=index(a,b);
   put q=;
run;

*proc contents data=test3 ;
*run;

data _null_;
   a = 'ABC.DEF (X=Y)';
   b = 'X=Y';
   x = index(a,b);
   put x=;
run;

 

 

5 REPLIES 5
ChrisNZ
Tourmaline | Level 20

The documentation is just one click away!

 

Functions and CALL Routines: INDEX Function - 9.2

Both leading and trailing spaces are considered part of the excerpt argument. To remove trailing spaces, include the TRIM function with the excerpt variable inside the INDEX function.

 

The string   'X=Y      '    is not found in variable A.

 

shahsn11
Fluorite | Level 6

Hi Chris,

 

Thanks for the quick response.

 

But, If we see both the data step code I have written and value in variable a and b are same. The second one gives me correct answer but the first one does not.

 

I would like to understand this behavior why the second result is giving me correct answer and first one is not. If I comment the length code in first datastep I get the correct answer , but I am not able to understand the logic behind this.

 

Thanks.

ChrisNZ
Tourmaline | Level 20
The logic is in my answer. When you don't define a length there are no trailing spaces added to the value you assign.
andreas_lds
Jade | Level 19

@ChrisNZ already explained why the index function in the first step fails to find the string: the variable b is always 14 chars long and padded with blanks, not matter what value is assigned to it. If you don't use length (or attrib) to define a variable, its length is automatically set depending on the first use.

shahsn11
Fluorite | Level 6

Thanks Chris and Andrea for answering the question ...  It makes complete sense now ...appreciate the help in clearing the doubt.

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 1625 views
  • 1 like
  • 3 in conversation