You can use the INDEX function in SAS to return the position of the first occurrence of a string within another character string.
This function uses the following basic syntax:
INDEX(source, excerpt)
where:
- source: The string to analyze
- excerpt: The string of characters to search for within source
The following example shows how to use this function in practice.
Example: Using the INDEX Function in SAS
Suppose we have the following dataset in SAS that contains a column of names:
/*create dataset*/
data original_data;
input name $25.;
datalines;
Andy Lincoln Bernard
Barren Michael Smith
Chad Simpson Arnolds
Derrick Smith Henrys
Eric Millerton Smith
Frank Giovanni Goode
;
run;
/*view dataset*/
proc print data=original_data;
We can use the INDEX function to search for the position of the first occurrence of the string “Smith” in each row:
/*find position of first occurrence of 'Smith' in name*/
data new_data;
set original_data;
first_smith = index(name, 'Smith');
run;
/*view results*/
proc print data=new_data;
The new column called first_smith displays the position of the first occurrence of the string ‘Smith’ in the name column.
If ‘Smith’ is not found at all, the INDEX function simply returns a value of 0.
It’s important to note that the INDEX function is case-sensitive, so if you search for ‘smith’ instead, the INDEX function will return 0 for each string:
/*find position of first occurrence of 'smith' in name*/
data new_data;
set original_data;
first_smith = index(name, 'smith');
run;
/*view results*/
proc print data=new_data;
To perform a case-insensitive search, you can use the lowcase() function to first convert each string to all lowercase and then search for ‘smith’ as follows:
/*find position of first occurrence of 'smith' in name*/
data new_data;
set original_data;
first_smith = index(lowcase(name), 'smith');
run;
/*view results*/
proc print data=new_data;
By first converting each string to all lowercase, we’re able to use the INDEX function to perform a case-insensitive search.
Additional Resources
The following tutorials explain how to use other common functions in SAS:
How to Use the SUBSTR Function in SAS
How to Use the COMPRESS Function in SAS
How to Use the FIND Function in SAS
How to Use the COALESCE Function in SAS