MATLAB字符串用单引号写出,类型是 char,本质上是一个 1×n 的字符数组。不少语言把字符串当成单独的基本类型,这里则按数组规则来处理。

创建字符串:单引号

my_string = 'Hello World'

whos 看变量信息:

whos

会显示类似:

Name         Size     Bytes  Class
my_string    1x11        22  char

注意 1x11:1 行 11 列,每个字符占一列。所以可以像取数组元素一样取字符:

s = 'MATLAB';
s(1)      % 'M'
s(end)    % 'B'
s(2:4)    % 'ATL'

字符串里的单引号:写两个

内容里要出现单引号,例如 online-compiler's,就连写两个单引号:

s = 'online-compiler''s editor'

得到的是 online-compiler's editor。这是 MATLAB 的转义写法,不是反斜杠。

字符与编码:char 和 uint8

既然是字符数组,就可以和编码互相转换:

s = 'AB';
uint8(s)          % 65 66(ASCII 码)
char([65 66 67])  % 'ABC'(数字码转回字符)

拼接:横着拼竖着拼

两个字符串横向拼在一起,用 [s1 s2]strcat

first = 'Ada';
last  = 'Lovelace';
[name1] = [first, ' ', last]     % 'Ada Lovelace'
[name2] = strcat(first, ' ', last) % 同样结果

strcat 会去掉字符串末尾的空格再拼接,[...] 则保留原样。很多段拼成一行时,可用 strjoin

words = {'red', 'blue', 'green'};
strjoin(words, '-')   % 'red-blue-green'

多行字符数组用 char,它会自动补空格把各行对齐:

profile = char('Ada Lovelace', 'Sr. Engineer', 'London')

大小写与空白处理

s = '  Hello World  ';
lower(s)        % 转小写
upper(s)        % 转大写
strtrim(s)      % 去掉首尾空白
deblank(s)      % 去掉末尾空白

易错点

  • 单引号和双引号不是一回事:旧版 MATLAB 双引号不合法,新版本双引号是 string 类型,和 char 有区别。入门阶段统一用单引号。
  • 字符串相等不要用 == 判断,用 strcmp,否则容易报错或结果不对。
  • char 数组每行要等长:直接写 ['abc'; 'defgh'] 会报错,用 char 函数可以自动补空格。