function s = insertAfter(str, pos, text)
% INSERTAFTER Insert substring after specified position
%    S = INSERTAFTER(STR, PAT, NEW) inserts NEW into STR
%    after the substrings matched by PAT and returns the result as
%    S. If PAT occurs multiple times in STR, then INSERTAFTER inserts
%    NEW after every nonoverlapping occurrence of PAT.
%
%    S = INSERTAFTER(STR, POS, NEW) inserts NEW directly after
%    numeric position POS. POS must be an integer from 0 to the number of
%    characters in STR.
%
%    NOTE: STR and NEW must be text, which means they can be a string 
%    array, a character vector, or a cell array of character vectors. PAT 
%    must be text or a pattern array. The output S has the same data type as STR.
%
%    Examples:
%        STR = "The quick fox";
%        PAT = 'quick';
%        NEW = ' brown';
%        insertAfter(STR,PAT,NEW)
%
%        % returns "The quick brown fox"
%
%        STR = 'peppers and onions';
%        PAT = 'peppers ';
%        NEW = 'mushrooms ';
%        insertAfter(STR,PAT,NEW)
%
%        % returns 'peppers mushrooms and onions'
%
%        STR = "It's 72 degrees out!";
%        PAT = digitsPattern;
%        NEW = '.0';
%        insertAfter(STR,PAT,NEW)
%
%        % returns "It's 72.0 degrees outside"
%
%    See also STRING/PLUS, INSERTBEFORE, REPLACE, REPLACEBETWEEN, PATTERN

%   Copyright 2016-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.insertAfter(pos, text);
        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
