strtrim — Remove leading and trailing whitespace from text inputs with MATLAB-compatible container semantics.
strtrim(text) removes leading and trailing whitespace while preserving internal spacing. It supports string, character and cellstr-style input containers.
Syntax
out = strtrim(str)Inputs
str- Type
Any- Required
- Yes
- Description
- String, character array, or cell array of text scalars to trim.
Returns
out- Type
Any- Description
- Trimmed text preserving the input container and element shape.
Errors
RunMat:strtrim:InvalidInput- When
- Input is not a string array, character array, or cell array of text scalars.
- Message
strtrim: first argument must be a string array, character array, or cell array of character vectors
RunMat:strtrim:CellElement- When
- Cell array contains a non-text element or non-row char array element.
- Message
strtrim: cell array elements must be string scalars or character vectors
RunMat:strtrim:InternalError- When
- Internal output container construction failed.
- Message
strtrim: internal error
Text containers
strtrim(text) removes leading and trailing whitespace without changing internal spacing. MATLAB-compatible mode retains significant whitespace U+0085, U+00A0, U+2007 and U+202F at either end. RunMat mode retains its broader Unicode-whitespace trimming behavior.
String scalars and arrays preserve type, dimensions and missing values. Character arrays are trimmed row by row: the row count stays fixed, and the width becomes that of the longest result, with shorter rows space-padded.
Cell arrays retain their layout. Character-vector cells are supported in both modes; cells containing string scalars are a RunMat-only extension. Numeric, logical, struct and integer data are not interpreted as character codes.
Placement and effects
strtrim runs on host text with no provider kernel or fusion route. Numeric or resident values reject before provider access rather than being implicitly converted or gathered.
The builtin uses no callbacks or external resources. Malformed input and output construction can throw.
Examples
Trim a string scalar
name = " RunMat ";
clean = strtrim(name)Expected output:
clean = "RunMat"Trim each element of a string array
labels = [" Alpha "; "Beta "; " Gamma"];
trimmed = strtrim(labels)Expected output:
trimmed = ["Alpha"; "Beta"; "Gamma"]Trim character-array rows
animals = char(' cat ', 'dog', ' cow ');
result = strtrim(animals)Expected output:
result = ['cat'; 'dog'; 'cow']Trim tabs and newlines
text = string([char(9) 'Metrics ' char(10)]);
clean = strtrim(text)Expected output:
clean = "Metrics"Trim a cell array of text
pieces = {' GPU ', " Accelerate", 'RunMat '};
out = strtrim(pieces)Expected output:
out = {'GPU', "Accelerate", 'RunMat'}Preserve missing strings
vals = [" ok "; string(missing); " trimmed " ];
trimmed = strtrim(vals)Expected output:
trimmed = ["ok"; <missing>; "trimmed"]Retain a nonbreaking space in MATLAB-compatible mode
text = [' Keep' char(160) ' '];
trimmed = strtrim(text)Expected output:
trimmed = ['Keep' char(160)]Using strtrim with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how strtrim changes the result.
Run a small strtrim example, explain the result, then change one input and compare the output.
FAQ
Does strtrim modify internal whitespace?⌄
No. Only leading and trailing whitespace is removed; interior spacing remains intact.
Which characters count as whitespace?⌄
Ordinary spaces, tabs and line breaks are trimmed. MATLAB-compatible mode preserves significant whitespace U+0085, U+00A0, U+2007 and U+202F; RunMat mode trims those too under its broader Unicode rule.
How are character arrays resized?⌄
Each row is trimmed independently. The output keeps its row count and uses the width of the longest trimmed row, padding shorter rows.
What happens to missing strings?⌄
Typed missing string elements remain missing. Literal text such as <missing> is ordinary text and is trimmed without changing its presence.
Can numeric or logical arrays be passed to strtrim?⌄
No. Non-text inputs raise a text-input error; integer arrays are not interpreted as character codes.
How does strtrim differ from strip?⌄
strtrim always removes whitespace at both ends. strip also supports custom characters and directional trimming.
What does strtrim do in MATLAB?⌄
It removes leading and trailing whitespace from a string or character array, preserving interior whitespace.
How is strtrim different from strip in MATLAB?⌄
strip also lets you choose left, right or both ends and supply the characters to remove.
Does strtrim work with string arrays?⌄
Yes. It trims each element and preserves the array shape and missing strings.
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 · strrep · strsplit · 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 strtrim is executed, line by line, in Rust.
- View the source for strtrim 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.