function s = replace(str, old, new) 
%REPLACE Replace segments from string elements
%   NEWSTR = REPLACE(STR,PAT,NEW) replaces all occurrences of PAT in STR
%   with NEW.
%
%
%   STR must be text, which means it can be a string array, a character
%   vector, or a cell array of character vectors. PAT can be text or a
%   pattern array. NEW must be text. If PAT is a text or pattern array, then 
%   NEW must be the same size as PAT or be scalar. All nonoverlapping 
%   occurrences of each element of PAT in STR are replaced by the 
%   corresponding element of NEW.
%
%   Examples:
%       STR = 'This is a good example';
%       PAT = 'good';
%       NEW = 'great';
%       replace(STR,PAT,NEW)
%
%       % returns 'This is a great example'
%
%       STR = ["c:\cookies.m";
%              "c:\candy.m";
%              "c:\calories.m"];
%       PAT = "c:";
%       NEW = "d:";
%       replace(STR,PAT,NEW)     
%
%       % returns ["d:\cookies.m";
%       %          "d:\cookies.m";
%       %          "d:\calories.m"] 
%
%       STR = "The answer is 42!";
%       PAT = digitsPattern;
%       NEW = "REDACTED";
%       replace(STR,PAT,NEW)
%
%       % returns "The answer is REDACTED!"
%    
%   See also STRREP, REGEXP, REGEXPREP, PATTERN, DIGITSPATTERN

%   Copyright 2015-2020 The MathWorks, Inc.

    narginchk(3, 3);
    
    if ~isTextStrict(str)
        error(fillMessageHoles('MATLAB:string:MustBeCharCellArrayOrString',...
                               'MATLAB:string:FirstInput'));
    end

    try
        s = string(str);
        s = s.replace(old, new);
        s = convertStringToOriginalTextType(s, str);
        
    catch ex
        if strcmp(ex.identifier, 'MATLAB:string:CannotConvertMissingElementToChar')
            error(fillMessageHoles('MATLAB:string:CannotInsertMissingIntoChar',...
                                   'MATLAB:string:MissingDisplayText'));
        end
        ex.throw;
    end

end 
