recipes : Text Processing : Searching for a string

Problem

You want to search for the presence of a smaller sub-string within another, larger, string.

Solution

The function strfind returns the starting indices of a defined substring within a larger string.

strfind('the dog chased the chicken', 'ch')
ans =

     9    20
Discussion

Sometimes you want to find where the sub-string is located, in which the case the indeces returned by strfind are useful. At other times, however, you may simply want to test whether the substring was present at all. Usefully, Matlab treats any array with non-zero values as true and an empty array (as produced when strfind fails to find a match) as false. This enables us to do:

str='I have many chickens';
if strfind(str,'chickens')
   disp('There are chickens')
end
>> There are chickens