http://kr.mathworks.com/help/matlab/ref/strrep.html
strrep
Find and replace substring
Syntax
modifiedStr
= strrep(origStr
, oldSubstr
, newSubstr
)
Description
modifiedStr
= strrep(origStr
, oldSubstr
, newSubstr
)
replaces all occurrences of the string oldSubstr
within string origStr
with the string 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 string 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
strrep
accepts input combinations of single strings, strings in scalar cells, and same-sized cell arrays of strings. If any inputs are cell arrays, strrep
returns a cell array.
The strrep
function does not find empty strings for replacement. That is, when origStr
and oldSubstr
both contain the empty string (''
), strrep
does not replace ''
with the contents of newSubstr
.
Before replacing strings, 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.