0

I'm running into an issue when using the index function to return the position of a string within a string.

So I have a concentrated list of surnames:

SMITH|JONES|DONALD

And I want to find the position of a string referenced from another column (SurnametoFind), so:

index(Surnames,'SMITH')

Works perfectly, however, when I reference the column I want to use the value to search on from (a list of single surnames which contains SMITH in one of the rows):

index(Surnames,SurnametoFind)

Returns 0.

This is within an SQL proc, so I also attempted with wildcards (in case index functions like PATINDEX on SQL Server):

index(Surnames,'%'||SurnametoFind||'%')

But this also returns zero.

Am I missing something about how the SurnametoFind column should be referenced in the index function?

Many thanks.

2 Answers 2

1

The main problem is that you have not accounted for the fact that SAS stores character variables as fixed length. So if SurnametoFind is long enough to store "DONALD" then when the value is "SMITH" there is at least one space after the H. So the string "SMITH " is not found in the string "SMITH|JONES|DONALD".

You can use the TRIM() function to remove the trialing spaces.

index(Surnames,trim(SurnametoFind))

But since your list is delimited you probably want to use the FINDW() function instead. With that you can tell it what character(s) delimit the "words" in the string that is being searched. It also has modifiers that will let you tell it to do the trimming (and other features) for you.

findw(Surnames,SurnametoFind,'|','t')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot - that solved it, much appreciated - and definitely a good shout on switching it to use findw.
0

You need to trim the blanks from SurnametoFind. Or use FIND function with T option may want to use I option also.

1    data _null_;
2       input Surnames :$20. SurnametoFind:$20.;
3       put (s:)(=);
4       x1 = index(surnames,surnametofind);
5       x2 = index(surnames,trim(surnametofind));
6       x3 = find(surnames,surnametofind,'IT');
7       put (x:)(=);
8       cards;

Surnames=SMITH|JONES|DONALD SurnametoFind=SMITH
x1=0 x2=1 x3=1
Surnames=SMITH|JONES|DONALD SurnametoFind=Smith
x1=0 x2=0 x3=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.