function s = insertBefore(str, pos, text)
% INSERTBEFORE Insert substring before specified position
%    S = INSERTBEFORE(STR, PAT, NEW) inserts NEW into STR
%    before the substrings matched by PAT and returns the result as
%    S. If PAT occurs multiple times in STR, then INSERTBEFORE inserts
%    NEW before every nonoverlapping occurrence of PAT.
%
%    S = INSERTBEFORE(STR, POS, NEW) inserts NEW directly before
%    numeric position POS. POS must be an integer between 1 and strlength(STR) + 1.
%
%    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 jumps";
%        PAT = ' fox';
%        NEW = ' brown';
%        insertBefore(STR,PAT,NEW)
%
%        % returns "The quick brown fox jumps"
%
%        STR = 'peppers and onions';
%        PAT = ' and';
%        NEW = ' mushrooms';
%        insertBefore(STR,PAT,NEW)
%
%        % returns 'peppers mushrooms and onions'
%
%        STR = "It's 40 degrees out!";
%        PAT = digitsPattern;
%        NEW = '-';
%        insertBefore(STR,PAT,NEW)
%
%        % returns "It's -40 degrees outside"
%
%    See also INSERTAFTER, REPLACE, REPLACEBETWEEN, EXTRACTBEFORE, EXTRACTAFTER, 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.insertBefore(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
