TExcelTAD
Home › MATLAB / Octave › String Functions

String Functions

MATLAB has a large toolbox of functions for building, searching, splitting and transforming text. This lesson covers the ones you'll use most often, all of which work on char arrays in both MATLAB and Octave.

Converting numbers and text

Function Converts
num2str(x) Number to text (about 4 decimals by default)
num2str(x, digits) / num2str(x, format) With precision or a format
int2str(x) Rounded integer to text
mat2str(A) Array to MATLAB syntax text
sprintf(format, ...) Anything, fully formatted
str2double(s) Text to number (NaN if invalid)
matlab · try it yourself
disp(num2str(pi))
disp(num2str(pi, 8))
disp(num2str(2.5, '%08.3f'))
disp(int2str(7.6))
disp(mat2str([1 2; 3 4]))
x = str2double('42.5') + 0.5
bad = str2double('forty')
3.1416
3.1415927
0002.500
8
[1 2;3 4]
x = 43
bad = NaN

str2double is the safe way to parse user text: invalid input becomes NaN, which you can test with isnan. Avoid str2num, which runs the text as code.

Trimming, padding and case

matlab · try it yourself
raw = '   Hello World   ';
fprintf('[%s]\n', strtrim(raw));
fprintf('[%s]\n', deblank(raw));      % removes trailing whitespace only
fprintf('[%s]\n', upper(strtrim(raw)));
fprintf('[%s]\n', [blanks(3) 'x']);
fprintf('[%-10s|%10s]\n', 'left', 'right');
[Hello World]
[   Hello World]
[HELLO WORLD]
[   x]
[left      |     right]

Searching and replacing

strfind returns the starting positions of a pattern, and strrep replaces every occurrence:

matlab · try it yourself
s = 'the cat sat on the mat';
disp(strfind(s, 'at'))
disp(isempty(strfind(s, 'dog')))
disp(strrep(s, 'the', 'a'))
disp(numel(strfind(s, 'the')))
fprintf('Starts with "the": %d\n', strncmp(s, 'the', 3));
    6   10   21
1
a cat sat on a mat
2
Starts with "the": 1

strfind returns an empty array when there is no match, so isempty(strfind(s, p)) is the portable "does not contain" test. (Modern MATLAB also has contains(s, p), startsWith and endsWith; Octave 11 has startsWith and endsWith but not contains.)

Splitting and joining

strsplit breaks text into a cell array of pieces at a delimiter (whitespace by default). strjoin does the reverse:

matlab · try it yourself
csv = 'red,green,,blue';
parts = strsplit(csv, ',')
disp(numel(parts))
words = strsplit('  one two   three ');
fprintf('%d pieces\n', numel(words));
strict = strsplit(csv, ',', 'CollapseDelimiters', false);
fprintf('%d pieces without collapsing\n', numel(strict));
disp(strjoin({'2025', '06', '30'}, '-'))
disp(strjoin(upper(parts), ' | '))
parts =
{
  [1,1] = red
  [1,2] = green
  [1,3] = blue
}

3
5 pieces
4 pieces without collapsing
2025-06-30
RED | GREEN | BLUE

By default strsplit collapses consecutive delimiters into one, so ',,' doesn't create an empty piece; pass 'CollapseDelimiters', false to keep it. Leading or trailing delimiters still produce empty pieces, which is why the whitespace example gives 5 pieces (an empty one at each end). upper applied to a cell array converts every element.

Regular expressions

regexp searches with patterns, and regexprep replaces matches. Patterns use standard regular-expression syntax: \d digit, \s space, \w word character, + one or more, * zero or more, (...) a group:

matlab · try it yourself
s = 'Order 66 shipped to Room 101 on day 7';
nums = regexp(s, '\d+', 'match')
values = str2double(nums);
disp(sum(values))
disp(regexprep(s, '\d+', '#'))
disp(regexprep('2025-06-30', '(\d+)-(\d+)-(\d+)', '$3/$2/$1'))
disp(regexprep('too    many     spaces', '\s+', ' '))
nums =
{
  [1,1] = 66
  [1,2] = 101
  [1,3] = 7
}

174
Order # shipped to Room # on day #
30/06/2025
too many spaces

In the replacement text, $1, $2, … refer to the groups captured by parentheses. regexp can return other things too: 'tokens' for the groups, 'start' for positions, 'names' for named groups.

Quick reference

Task Function
Length length(s), numel(s)
Upper/lower case upper, lower
Remove surrounding whitespace strtrim
Find a substring strfind, regexp
Replace strrep, regexprep
Split / join strsplit, strjoin
Compare strcmp, strcmpi, strncmp
Reverse fliplr(s) or s(end:-1:1)
Number ↔ text num2str, sprintf, str2double

Test yourself

What does str2double('12abc') return?

  1. 12
  2. '12'
  3. NaN
  4. An error

What does strsplit('a-b-c', '-') return?

  1. 'abc'
  2. A 1x3 cell array {'a', 'b', 'c'}
  3. A 3x1 char matrix
  4. [1 2 3]

What is regexprep('a1b22c', '\d+', '')?

  1. 'abc'
  2. 'a1b22c'
  3. '122'
  4. 'a b c'