Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

strrep

Find and replace substring

Syntax

modifiedStr = strrep(origStr, oldSubstr, newSubstr)

Description

modifiedStr = strrep(origStr, oldSubstr, newSubstr) replaces all occurrences of oldSubstr within origStr with newSubstr.

Examples

Replace text in a character array:

claim = 'This is a good example.';
new_claim = strrep(claim, 'good', 'great')

MATLAB® returns:

new_claim =
This is a great example.

Replace text in a cell array:

c_files = {'c:\cookies.m'; ...
           'c:\candy.m';   ...
           'c:\calories.m'};
d_files = strrep(c_files, 'c:', 'd:')

MATLAB returns:

d_files = 
    'd:\cookies.m'
    'd:\candy.m'
    'd:\calories.m'

Replace text in a cell array with values in a second cell array:

missing_info = {'Start: __'; ...
                'End: __'};

dates = {'01/01/2001'; ...
         '12/12/2002'};

complete = strrep(missing_info, '__', dates)

MATLAB returns:

complete = 
    'Start: 01/01/2001'
    'End: 12/12/2002'

Compare the use of strrep and regexprep to replace a character vector with a repeated pattern:

repeats = 'abc 2 def 22 ghi 222 jkl 2222';
indices = strfind(repeats, '22')

using_strrep = strrep(repeats, '22', '*')
using_regexprep = regexprep(repeats, '22', '*')

MATLAB returns:

indices =
    11    18    19    26    27    28

using_strrep =
abc 2 def * ghi ** jkl ***

using_regexprep =
abc 2 def * ghi *2 jkl **

More About

collapse all

Tips

  • strrep accepts input combinations of character vectors, scalar cells that contain character vectors, and same-sized cell arrays of character vectors. If any inputs are cell arrays, strrep returns a cell array.

  • The strrep function does not find empty character vectors for replacement. That is, when origStr and oldSubstr both contain the empty character vector (''), strrep does not replace '' with the contents of newSubstr.

  • Before replacing character vectors, strrep finds all instances of oldSubstr in origStr, like the strfind function. For overlapping patterns, strrep performs multiple replacements. See the final example in the Examples section.

See Also

|

Introduced before R2006a

Was this topic helpful?