MATLAB: How to replace a word with another word in a cell array (case insensitive)

cell arraystring

Hi I am trying to replace words found in a string with a given value (case insensitive)
str = 'lemon lemontea Lemongrass lime';
replaceword = 'lemon' %case insensitive
withthis = {'berry', 'apple', 'flower'};
Assume that we will be given with enough number of words to replace all the occurance of the word
I want to return this:
newstr = 'berry appletea flowergrass lime';
I tried to use strrep but it would replace for Lemon…

Best Answer

Method one: loop and regexprep:
for k = 1:numel(withthis)
str = regexprep(str,replaceword,withthis{k},'once','ignorecase');
end
Method two: regexpi and indexing:
>> spl = regexpi(str,replaceword,'split');
>> spl(2,1:end-1) = withthis;
>> str = sprintf('%s',spl{:})
str =
berry appletea flowergrass lime