Reading — step 1 of 5
Learn
~1 min readLinear Algebra, Strings, Plotting
Octave strings are character arrays. Strings of different lengths can't go in a regular array — use cell arrays.
Strings
s = "hello";
double_s = double(s) %% [104 101 108 108 111] (ASCII codes)
len = length(s) %% 5
upper = upper(s) %% "HELLO"
rev = fliplr(s) %% "olleh"
s(1) %% "h" (1-indexed!)
s(2:4) %% "ell"
String concatenation
["hello", " ", "world"] %% "hello world" (regular array concat)
strcat("hello", " world") %% beware: strcat strips trailing spaces!
sprintf("%s %s", a, b) %% safer
sprintf and printf
sprintf("%d items, $%.2f each", 3, 9.99)
%% prints "3 items, $9.99" — same format syntax as C
printf("%s scored %d (%.1f%%)\n", "Ada", 95, 95.0)
%% writes to stdout
strsplit / strjoin
parts = strsplit("a,b,c,d", ",") %% {"a", "b", "c", "d"} — cell array
strjoin({"a", "b", "c"}, "-") %% "a-b-c"
Cell arrays — heterogeneous
Regular [] arrays must be all-same-size. Cell arrays {} can hold anything:
stuff = {"Ada", 36, [1 2 3]}
stuff{1} %% "Ada"
stuff{2} %% 36
stuff{3} %% [1 2 3]
Note {} for ACCESS too — stuff{i} gets the contents, stuff(i) returns a 1-element cell array.
Common string funcs
strtrim(" hi ") %% "hi"
strrep("hello", "l", "L") %% "heLLo"
strfind("banana", "an") %% [2 4]
regexp("abc123", "\\d+", "match") %% {"123"}
strcmp("foo", "foo") %% true (1)
str2num("42") %% 42
num2str(42) %% "42"
Multi-line strings
s = sprintf("line 1\nline 2\nline 3")
No triple-quote literals — use sprintf or string concatenation.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…