Find one string within another




k = strfind(str, pattern) searches str for occurrences of pattern. The output, k, indicates the starting index of each occurrence of pattern in str. If pattern is not found strfind returns an empty array, []. The strfind function executes a case sensitive search.

  • If str is a string, strfind returns a vector of type double.

  • If str is a cell array, strfind returns a cell array of vectors of type double.


collapse all

Find String Pattern

Define string S as follows:

S = 'Find the starting indices of the pattern string';

Find the pattern in in string S.

k = strfind(S, 'in')
k =

     2    15    19    45

There are four instances of the substring, in, found in S.

Find the pattern In in string S.

k = strfind(S, 'In')
k =


Since strfind is case sensitive, the string, In, is not found in S, k is an empty array.

Find the blank spaces in string S.

k = strfind(S, ' ')
k =

     5     9    18    26    29    33    41

There are seven occurrences of blank spaces in the string S.

Find String in Cell Array of Strings

Define the cell array of strings, cstr, as follows:

 cstr = {'How much wood would a woodchuck chuck';
         'if a woodchuck could chuck wood?'};

Find the pattern, wood, in cell array cstr.

 idx = strfind(cstr, 'wood')
idx = 

    [1x2 double]
    [1x2 double]

Examine the output cell array to find the instances of wood.

ans =

    10    23

ans =

     6    28

The pattern, wood, occurs at indices 10 and 23 in the first string and at indices 6 and 28 in the second string.

Input Arguments

collapse all

str — Data to be searchedstring | cell array of strings

Data to be searched, specified as a string or cell array of strings.

Data Types: char | cell

pattern — Search patternstring

Search pattern, specified as a string.

Data Types: char

Output Arguments

collapse all

k — Indices of occurrences of patternarray

Indices of occurrences of pattern, returned as an array. If pattern is not found, then k is an empty array, [].

  • If str is a string, k is an array of doubles indicating the index of each occurrence of pattern.

  • If str is a cell array of strings, k is a cell array with each element being an array of type double corresponding to the indices of each occurrence of pattern in the corresponding element of str.

More About

expand all


  • The strfind function does not find a pattern of empty strings, '', within str.

Introduced before R2006a

Was this topic helpful?