plato/string_operations.m

61 lines
1.7 KiB
Matlab

clear
% two types for representing text:
% 'char' arrays and 'string' arrays
char_scalar = 'a';
char_array = 'abc';
% 'abc' is the same as ['a' 'b' 'c']
assert(all(char_array == ['a' 'b' 'c']));
assert(all(size(char_array) == [1 3]));
% single quotes are escaped by doubling
escaped = 'this is a ''char array'''; % this is a 'char array'
char_matrix = ['abc'; 'def'];
assert(numel(char_matrix) == 6);
% string arrays provide functions to deal with them
% this two are not equivalent!
string_scalar = "Hello World!"; % < 1x1 string array
string_array = ["Hello", "World"]; % < 1x2 string array
assert(all(string_scalar ~= string_array));
% convert a char array to a string
msg = string(char_array);
assert(ischar(char_array));
assert(isstring(msg));
% convert a number to a char array (despite the name!!)
one = int2str(1);
pi = num2str(3.14);
arr = num2str([1 3]);
assert(all(one == '1'));
assert(all(pi == '3.14'));
assert(all(arr == '1 3'));
% convert something to a string
one_s = string(1);
pi_s = string(3.14);
arr_s = string([1 3]);
cell_s = string({1 10}); % cannot do this with num2str
assert(one_s == "1");
assert(pi_s == "3.14");
assert(all(arr_s == ["1", "3"]));
assert(isequal(cell_s, ["1", "10"])); % note that the result is a string array
% get a char array length
assert(numel('abc') == 3); % obvious
% get a string length: less obvious
assert(numel("abc") == 1);
assert(strlength("abc") == 3);
% concatenate strings: lot of ways (char, strings, cell of strings... plus
% dimensionality)
% basic way:
assert(isequal("Hello" + " World", "Hello World"));
% more correct (deals with char arrays and cell arrays of strings)
assert(isequal(append("Hello", ' ', "World"), "Hello World"));