Documentation

This is machine translation

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

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this 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

Tall Array Support

This function supports tall arrays with the limitations:

  • The original string must be a tall array of strings or a tall cell array of character vectors.

  • The old string and new string inputs can be single strings or tall arrays of strings with the same size.

For more information, see Tall Arrays.

Tips

  • strrep accepts input combinations of character vectors, cell arrays of character vectors, and string arrays. The type of modifiedStr is the same as origStr.

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

  • Before replacing text, 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.

Introduced before R2006a

Was this topic helpful?