strrep — Replace non-overlapping substring occurrences in text inputs with MATLAB-compatible container behavior.
strrep(str, old, new) replaces every non-overlapping occurrence of old with new. It supports MATLAB-compatible string, char, and cellstr-style inputs with element-wise replacement semantics.
Syntax
newStr = strrep(str, old, new)Inputs
str- Type
Any- Required
- Yes
- Description
- Input text (string/char/cell).
old- Type
Any- Required
- Yes
- Description
- Pattern text scalar (string or char row).
new- Type
Any- Required
- Yes
- Description
- Replacement text scalar matching old's data type family.
Returns
newStr- Type
Any- Description
- Text with pattern occurrences replaced, preserving input container kind.
Errors
RunMat:strrep:TooManyOutputs- When
- More than one output is requested.
- Message
strrep: too many output arguments
RunMat:strrep:InvalidInput- When
- First argument is not a string array, char array, or cell array of text scalars.
- Message
strrep: first argument must be a string array, character array, or cell array of character vectors
RunMat:strrep:PatternType- When
- old/new arguments are not string scalars or character vectors.
- Message
strrep: old and new must be string scalars or character vectors
Behavior
String scalars remain strings. Typed missing string values (displayed as <missing>) propagate unchanged; literal <missing> text remains ordinary text.
String arrays are processed element-wise while preserving their full shape and orientation.
Character arrays are handled row by row. Rows expand or shrink as needed and are padded with spaces so the result stays a rectangular char array, just like MATLAB.
Cell arrays must contain character vectors or string scalars. The result is a cell array of identical size where each element has had the replacement applied.
The old and new arguments must be string scalars or character vectors of the same data type.
old can be empty. In that case, strrep inserts new before the first character, between existing characters, and after the final character.
Integer values in any of the three text roles are rejected rather than treated as character codes or formatted numbers.
Placement and effects
Replacement runs on host text. Numeric and provider-resident inputs are unsupported and reject before provider access.
This pure host operation may throw and may suspend at admitted gathers. It performs no callbacks, workspace/environment mutation, filesystem operations, randomness, or Clock reads. There is no GPU kernel, fusion route, or distributed support. VM and native calls share the canonical portable Runtime binding; these declarations are not execution evidence.
No. strrep accepts host text and returns host text. Provider-resident numeric values are unsupported and reject before access.
strrep computes replacements on host text and returns a host text container of the corresponding kind. Numeric resident values reject before provider access rather than being gathered and implicitly converted to text.
Current implementation frontier
Character arrays with non-singleton dimensions beyond two, including those inside cells and delimiter controls, reject before row extraction. String and cell array geometry follows the per-entry behavior described here.
The host implementation also processes string arrays and character matrices inside cells, broader than scalar cellstr prose. Typed missing strings remain distinct from literal text. The retired GPU example was not executable: gpuArray has no text representation. Its host equivalent is asserted below. General managed text allocation remains incomplete.
Examples
Replacing a word inside a string scalar
txt = "RunMat turbo mode";
result = strrep(txt, "turbo", "accelerate")Updating every element of a string array
labels = ["GPU planner", "CPU planner"];
updated = strrep(labels, "planner", "pipeline")Preserving rectangular shape in character arrays
chars = char("alpha", "beta ");
out = strrep(chars, "a", "A")Applying replacements inside a cell array of character vectors
C = {'Kernel Fusion', 'GPU Planner'};
renamed = strrep(C, ' ', '_')Inserting text with an empty search pattern
stub = "abc";
expanded = strrep(stub, "", "-")Leaving missing string values untouched
vals = ["RunMat", string(missing), "Accelerate"];
out = strrep(vals, "RunMat", "RUNMAT")Replace host text (corrected GPU text example)
g = "native-code";
host = strrep(g, "code", "path")Using strrep with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how strrep changes the result.
Run a small strrep example, explain the result, then change one input and compare the output.
FAQ
Which input types does strrep accept?⌄
String scalars, string arrays, character vectors, character arrays, and cell arrays of character vectors. The old and new arguments must be string scalars or character vectors of the same data type.
Does strrep support multiple search terms at once?⌄
No. Use the newer replace builtin if you need to substitute several search terms in a single call.
How does strrep handle missing strings?⌄
Missing string scalars remain <missing> and are returned unchanged, even when the search pattern matches ordinary text.
Will rows of a character array stay aligned?⌄
Yes. Each row is replaced individually, then padded with spaces so that the overall array stays rectangular, matching MATLAB exactly.
What happens when old is empty?⌄
RunMat mirrors MATLAB: new is inserted before the first character, between every existing character, and after the last character.
Does strrep run on the GPU?⌄
No GPU text representation is supported. Numeric GPU values are not text and reject before provider access; convert supported host data to strings explicitly before calling strrep.
Can I mix strings and character vectors for old and new?⌄
No. MATLAB requires old and new to share the same data type. RunMat enforces the same rule and raises a descriptive error when they differ.
How do I replace text stored inside cell arrays?⌄
strrep traverses the cell array, applying the replacement to each character vector or string scalar element and returning a cell array of the same shape.
Related Strings functions
Transform
append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · extractBetween · insertAfter · insertBefore · join · lower · pad · replace · replaceBetween · reverse · split · splitlines · strcat · strip · strjoin · strjust · strsplit · strtrim · upper
Text Analytics
addDependencyDetails · addEntityDetails · addLemmaDetails · addPartOfSpeechDetails · addSentenceDetails · addTypeDetails · bagOfNgrams · bagOfWords · cosineSimilarity · doc2sequence · encode · extractFileText · extractHTMLText · fastTextWordEmbedding · findElement · getAttribute · htmlTree · ind2word · isVocabularyWord · normalizeWords · readWordEmbedding · removeLongWords · removeShortWords · removeStopWords · removeWords · stopWords · tokenDetails · tokenizedDocument · trainWordEmbedding · vaderSentimentScores · vec2word · word2ind · word2vec · wordEncoding · writeWordEmbedding
Core
blanks · char · compose · convertCharsToStrings · convertContainedStringsToChars · convertStringsToChars · genvarname · int2str · isletter · isspace · isStringScalar · isstrprop · mat2str · native2unicode · newline · num2str · sprintf · sscanf · str2double · str2num · strcmp · strcmpi · string · string.empty · strings · strlength · strncmp · strncmpi · strtok · unicode2native
Search
contains · endsWith · matches · startsWith · strfind
Pattern
digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern
Source you can read
Every RunMat function's source is public. Read exactly how strrep is executed, line by line, in Rust.
- View the source for strrep in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.