How to Use the FINDW Function in SAS

This paper examines the FINDW function in SAS, a powerful tool for locating specific words and phrases within a text string. It explores the syntax and usage of the function, and provides examples to illustrate its application. It explains how to use the FINDW function to locate partial words, how to use variables in the search, and how to limit the search to specific locations within the text. Finally, it discusses the potential uses and benefits of the FINDW function.


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.

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;

FIND vs. FINDW functions in SAS

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.

The following tutorials explain how to use other common functions in SAS:

x