Method Reference: string.insertBefore

string: newstr = insertBefore (str, pat, newtext)
string: newstr = insertBefore (str, pos, newtext)

Insert text before a pattern or position.

newstr = insertBefore (str, pat, newtext) inserts the text newtext into each element of str before every non-overlapping occurrence of the substring pat. pat can be a string array, a character vector, or a cell array of character vectors, and must either be a scalar, applied to every element of str, or be of the same size as str and applied element-wise. If pat is not found in an element, that element is returned unchanged.

newstr = insertBefore (str, pos, newtext) inserts newtext before the character position pos, that is, between the characters at positions pos-1 and pos. pos must be a positive integer not exceeding the length of the corresponding element of str, and must be either a scalar or the same size as str.

newtext can be a string array, a character vector, or a cell array of character vectors, and must be either a scalar, inserted at every position, or of the same size as str. newstr is a string array of the same size as str. Missing values in str are preserved, and a missing value in newtext makes the corresponding element of newstr missing.

Source Code: string

Example: 1

insertBefore inserts text right before each occurrence of a substring — for example a suffix just before a file extension.

 files = string ({'cat.txt'; 'dog.txt'})
files =
  2x1 string array

    "cat.txt"    
    "dog.txt"
 insertBefore (files, '.txt', '_bak')
ans =
  2x1 string array

    "cat_bak.txt"    
    "dog_bak.txt"