String Arrays
Characters & Strings introduced the two ways MATLAB stores text: char arrays ('...') and string arrays ("..."). This lesson takes a proper look at string arrays, the text type modern MATLAB code and documentation use by default, and shows how to do the same jobs in code that also runs in GNU Octave.
Note: Octave 11 has no
stringclass. In Octave"..."creates an ordinary char array (with backslash escapes such as\tand\nprocessed). The MATLAB blocks below are shown with MATLAB's output; every runnable example uses char arrays and cell arrays, which work in both.
One element = one piece of text
The key difference is what one element holds. A char array is a vector of characters, so 'Grace' has five elements. A string array stores a whole piece of text per element, so "Grace" is a 1x1 array, and a list of names is simply a 1xN string array:
% MATLAB R2017a or later
names = ["Ada" "Grace" "Linus"]
numel(names)
strlength(names)
names(2)MATLAB output:
names =
1×3 string array
"Ada" "Grace" "Linus"
ans =
3
ans =
3 5 5
ans =
"Grace"numel counts texts, while strlength counts characters in each one. names(2) returns a 1x1 string; names{2} returns its contents as a char array, which is handy when calling older functions that expect char.
In Octave (and in older MATLAB code) the same list is a cell array of char arrays, often called a cellstr. The everyday operations look very similar:
names = {'Ada', 'Grace', 'Linus'};
fprintf('%d names\n', numel(names));
disp(cellfun(@length, names))
second = names{2};
fprintf('second: %s (%s)\n', second, class(second));
disp(iscellstr(names))
disp(class("double quotes in Octave"))3 names
3 5 5
second: Grace (char)
1
char
cellfun(@length, names) plays the role of strlength. See Cell Arrays for the difference between names(2) (a 1x1 cell) and names{2} (the text inside).
Creating and converting
| MATLAB (string) | What it does | Octave-compatible equivalent |
|---|---|---|
"text" |
A string scalar | 'text' |
strings(1, 3) |
Three empty strings "" |
repmat({''}, 1, 3) |
string(42) |
Number to string "42" |
num2str(42) |
string({'a','b'}) |
cellstr to string array | (already a cellstr) |
cellstr(s) / char(s) |
string array to cellstr / char | — |
double("3.5") |
Parse a number | str2double('3.5') |
compose("id%02d", 1:3) |
Formatted text per element | arrayfun(@(k) sprintf('id%02d', k), 1:3, 'UniformOutput', false) |
double("3.5") is a nice MATLAB shortcut: on a string it parses the number, but on a char array it returns the character codes. str2double works on both and is the portable choice.
ids = arrayfun(@(k) sprintf('id%02d', k), 1:3, 'UniformOutput', false)
values = str2double({'3.5', '-2', 'oops'})
empties = repmat({''}, 1, 3);
disp(all(cellfun(@isempty, empties)))ids =
{
[1,1] = id01
[1,2] = id02
[1,3] = id03
}
values =
3.5000 -2.0000 NaN
1
Joining with +
With string arrays, + concatenates text, and numbers on either side are converted automatically. It also works element by element on whole arrays:
% MATLAB only
total = 42;
msg = "Total: " + total + " items"
files = "report_" + (1:3) + ".csv"MATLAB output:
msg =
"Total: 42 items"
files =
1×3 string array
"report_1.csv" "report_2.csv" "report_3.csv"With char arrays, + would add character codes. Use square brackets, sprintf or strcat instead; strcat accepts a cell array and appends to every element:
total = 42;
msg = sprintf('Total: %d items', total)
files = strcat('report_', {'1', '2', '3'}, '.csv')
greeting = [upper('ada') ', welcome!']msg = Total: 42 items
files =
{
[1,1] = report_1.csv
[1,2] = report_2.csv
[1,3] = report_3.csv
}
greeting = ADA, welcome!
Warning:
strcatremoves trailing whitespace from char arguments, sostrcat('a ', 'b')is'ab'. Inside a cell array the spaces are kept. When spacing matters, use[...]orsprintf.
Comparing and sorting
A real advantage of strings: == compares whole texts, even of different lengths, and works across an array.
% MATLAB only
names = ["Ada" "Grace" "Linus"];
names == "Grace"
sort(["pear" "Apple" "fig"])MATLAB output:
ans =
1×3 logical array
0 1 0
ans =
1×3 string array
"Apple" "fig" "pear"For char arrays == compares character by character and fails when the lengths differ, so use strcmp, which also accepts a cell array and returns one logical per element. sort and ismember work on cellstr too:
names = {'Ada', 'Grace', 'Linus'};
disp(strcmp(names, 'Grace'))
disp(sort({'pear', 'Apple', 'fig'}))
[found, where] = ismember({'Linus', 'Bob'}, names) 0 1 0
{
[1,1] = Apple
[1,2] = fig
[1,3] = pear
}
found =
1 0
where =
3 0
Sorting is by character code, so uppercase letters (codes 65 to 90) come before lowercase ones. To sort ignoring case, sort lower(names) and use the second output of sort as the order.
The modern text functions
MATLAB R2016b added a family of functions that read like English and accept strings, char arrays and cellstr alike. Octave 11 implements only a few of them (startsWith, endsWith), so here is each one with a portable replacement:
| MATLAB | Example | Portable equivalent |
|---|---|---|
contains(s, p) |
contains("report.pdf", "port") |
~isempty(strfind(s, p)) |
startsWith / endsWith |
endsWith(f, ".csv") |
the same (Octave has them), or strncmp |
replace(s, old, new) |
replace(s, "-", "_") |
strrep(s, old, new) |
strip(s) |
strip(" hi ") |
strtrim(s) |
split(s, d) / join(p, d) |
split("a,b,c", ",") |
strsplit(s, d) / strjoin(p, d) |
extractBefore(s, p) / extractAfter(s, p) |
extractAfter("key=val", "=") |
strfind + indexing, or regexp |
extractBetween(s, a, b) |
extractBetween(s, "[", "]") |
regexp(s, '\[(.*?)\]', 'tokens') |
pad(s, n) |
pad("ab", 5) |
sprintf('%-5s', s) |
insertAfter, eraseBetween, count |
regexprep, numel(strfind(...)) |
Here is how they look in MATLAB on a small file list:
% MATLAB only
files = ["data_2024.csv" "notes.txt" "data_2025.csv"];
csvFiles = files(endsWith(files, ".csv"))
years = extractBetween(csvFiles, "data_", ".csv")
contains(files, "data")MATLAB output:
csvFiles =
1×2 string array
"data_2024.csv" "data_2025.csv"
years =
1×2 string array
"2024" "2025"
ans =
1×3 logical array
1 0 1The same job with cellstr in both MATLAB and Octave. strfind on a cell array returns a cell of position vectors, so cellfun(@isempty, ...) turns it into a logical "not found" mask:
files = {'data_2024.csv', 'notes.txt', 'data_2025.csv'};
isCsv = endsWith(files, '.csv');
csvFiles = files(isCsv)
tok = regexp(csvFiles, 'data_(\d+)\.csv', 'tokens', 'once');
years = cellfun(@(t) t{1}, tok, 'UniformOutput', false)
hasData = ~cellfun(@isempty, strfind(files, 'data'))
renamed = strrep(files, '_', '-')csvFiles =
{
[1,1] = data_2024.csv
[1,2] = data_2025.csv
}
years =
{
[1,1] = 2024
[1,2] = 2025
}
hasData =
1 0 1
renamed =
{
[1,1] = data-2024.csv
[1,2] = notes.txt
[1,3] = data-2025.csv
}
regexp with the 'once' option returns, for each file, the captured groups of the first match; the next lesson, Regular Expressions, explains tokens in detail.
Splitting and joining text
split returns a string array (a column for a scalar input), and join glues the elements back together:
% MATLAB only
parts = split("2025-06-30", "-")'
join(parts, "/")MATLAB output:
parts =
1×3 string array
"2025" "06" "30"
ans =
"2025/06/30"strsplit and strjoin do the same with char arrays and cellstr (covered in String Functions). strtrim and upper also accept a whole cell array:
parts = strsplit('2025-06-30', '-');
disp(strjoin(parts, '/'))
raw = {' apple ', 'Banana ', ' cherry'};
clean = strtrim(raw);
fprintf('[%s] ', clean{:}); fprintf('\n');
fprintf('%s\n', strjoin(upper(clean), ', '));
nums = str2double(strsplit('4 8 15 16', ' '));
fprintf('sum = %d\n', sum(nums));2025/06/30
[apple] [Banana] [cherry]
APPLE, BANANA, CHERRY
sum = 43
fprintf('[%s] ', clean{:}) reuses the format for each element of the comma-separated list clean{:}, a quick way to print every text in a cell array.
Missing text
String arrays have a special <missing> value (like NaN for numbers), created with missing or produced by string(NaN); ismissing detects it. An empty string "" is a different thing: a real piece of text with zero characters.
% MATLAB only
s = ["red" missing ""];
ismissing(s)
strlength(s)MATLAB output:
ans =
1×3 logical array
0 1 0
ans =
3 NaN 0A cellstr has no missing value; the usual convention is to store '' and test with cellfun(@isempty, c).
Which should I use?
- Writing for modern MATLAB only: string arrays are the clearest choice, especially for lists of text.
- Sharing code with Octave users or older MATLAB versions: use char arrays for single texts and cellstr for lists. Almost every MATLAB function that accepts strings also accepts cellstr.
- Calling an old function that rejects strings: convert with
char(s)for one text orcellstr(s)for an array.
Learn more: String Functions, Cell Arrays and Regular Expressions.
Test yourself
In MATLAB, what is numel(["Ada" "Grace"])?
- 2
- 8
- 1
- An error
What does "a" create in GNU Octave 11?
- A char array
- A string scalar
- A cell array
- An error
Which call is a portable replacement for contains(s, 'abc') when s is a char array?
~isempty(strfind(s, 'abc'))strcmp(s, 'abc')s == 'abc'strtrim(s, 'abc')