You can use the FINDW function in SAS to return the position of the first character of a word that occurs within a string.
This function uses the following basic syntax:
FINDW(string, word)
where:
- string: The string to analyze
- word: The word to search for within string
The following example shows how to use this function in practice.
Example: Using the FINDW Function in SAS
Suppose we have the following dataset in SAS that contains a column of phrases:
/*create dataset*/
data original_data;
input phrase $40.;
datalines;
A pig is my favorite animal
My name is piglet
Pigs are so cute
Here is a baby pig
His name is piggie
;
run;
/*view dataset*/
proc print data=original_data;
We can use the FINDW function to search for the position of the first occurrence of the word ‘pig’ in the phrase column:
/*find position of first occurrence of 'pig' in phrase column*/
data new_data;
set original_data;
findw_pig = findw(phrase, 'pig');
run;
/*view results*/
proc print data=new_data;
The new column called findw_pig displays the position of the first occurrence of the word ‘pig’ in the phrase column.
If the word ‘pig’ never occurs in the phrase column then the FINDW function simply returns a value of 0.
For example, from the output we can see:
The position of the first occurrence of the word ‘pig’ in the first phrase is 3.
The second row does not contain the word ‘pig’ by itself in the phrase, so a value of 0 is returned.
And so on.
The Difference BETWEEN FIND and FINDW Functions
The FIND function in SAS returns the position of the first occurrence of a particular substring in another string.
By contrast, the FINDW function returns the position of the first occurrence of a particular word in another string.
By definition, a word must have a space before and after it.
The following example illustrates the difference between the FIND and FINDW functions:
/*create new dataset*/
data new_data;
set original_data;
find_pig = find(phrase, 'pig');
findw_pig = findw(phrase, 'pig');
run;
/*view new dataset*/
proc print data=new_data;
The find_pig column displays the position of the first occurrence of the substring ‘pig’ in the phrase column.
The findw_pig column displays the position of the first occurrence of the word ‘pig’ in the phrase column.
Additional Resources
The following tutorials explain how to use other common functions in SAS:
How to Use the FIND Function in SAS
How to Use the FINDC Function in SAS
How to Use the SUBSTR Function in SAS