You can use the FIND function in SAS to find the position of the first occurrence of some substring within a string.
Here are the two most common ways to use this function:
Method 1: Find Position of First Occurrence of String
data new_data;
set original_data;
first_occurrence = find(variable_name, "string");
run;
Method 2: Find Position of First Occurrence of String (Ignoring Case)
data new_data;
set original_data;
first_occurrence = find(variable_name, "string", "i");
run;
The “i” argument tells SAS to ignore the case when searching for the substring.
The following examples show how to use each method with the following dataset in SAS:
/*create dataset*/
data original_data;
input phrase $1-25;
datalines;
The fox ran fast
That is a quick FOX
This fox is a slow fox
The zebra is cool
;
run;
/*view dataset*/
proc print data=original_data;
Example 1: Find Position of First Occurrence of String
The following code shows how to find the position of the first occurrence of “fox” in each string:
data new_data;
set original_data;
first_fox = find(phrase, "fox");
run;
Here’s how to interpret the output:
- The fox ran fast (First occurrence is at position 5)
- That is a quick FOX (The lowercase string “fox” never occurs)
- This fox is a slow fox (First occurrence is at position 6)
- The zebra is cool (The string “fox” never occurs)
Example 2: Find Position of First Occurrence of String (Ignoring Case)
The following code shows how to find the position of the first case-insensitive occurrence of “fox” in each string:
data new_data;
set original_data;
first_fox = find(phrase, "fox", "i");
run;
Here’s how to interpret the output:
- The fox ran fast (First occurrence is at position 5)
- That is a quick FOX (First occurrence of “fox” is at position 17)
- This fox is a slow fox (First occurrence is at position 6)
- The zebra is cool (The string “fox” never occurs)
Additional Resources
The following tutorials explain how to perform other common tasks in SAS:
How to Normalize Data in SAS
How to Replace Characters in a String in SAS
How to Replace Missing Values with Zero in SAS
How to Remove Duplicates in SAS