recipes : Text Processing : Searching for a string


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


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

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')
>> There are chickens