
2.5 字符串
字符串是MATLAB语言的一个重要组成部分,MATLAB语言提供强大的字符串处理功能。本节主要介绍字符串的创建,字符串的操作和字符串的转换等内容。
2.5.1 字符串的创建
在MATLAB语言中,字符串一般以ASCII码形式存储,以行向量形式存在,并且每个字符占用两字节的内存。在MATLAB语言中,创建一个字符串可以用下面几种方法:
(1)直接将字符内容用单引号('')括起来,例如:

字符串的存储空间如下所示,所定义的字符串有12个字符,每个字符占用两字节的内存。

若要显示单引号(')字符,需要使用两个单引号,例如:

(2)用方括号连接多个字符串组成一个长字符串,例如:

(3)用函数strcat把多个字符串水平连接合并成一个长字符串,strcat函数语法格式如下:

例如:

(4)用函数strvcat把多个字符串连接成多行字符串,strvcat函数语法格式如下:

例如:

MATLAB语言可以用abs或者double函数获取字符串所对应的ASCII码数值矩阵。相反,可以用char函数把ASCII码转换为字符串。例如:

【例2-5】 已知一个字符串向量str='It is a Green Bird',完成以下任务:
(1)计算字符串向量的字符个数;
(2)显示'a Green Bird';
(3)将字符串倒序重排;
(4)将字符串中的大写字母变成相应的小写字母,其余字符不变。
MATLAB程序代码如下:

程序运行结果如下:

2.5.2 字符串的操作
1.字符串比较
MATLAB语言比较两个字符串是否相同的常用函数有strcmp、strncmp、strcmpi和strncmpi 4个,字符串比较函数的调用格式及功能说明如表2-2所示。
表2-2 字符串比较函数格式及功能

例如:

2.字符串查找和替换
MATLAB语言查找与替换字符串的常用函数有5个:strfind、findstr、strmatch、strtok和strrep。字符串查找函数的调用格式及功能说明如表2-3所示。
表2-3 字符串查找函数

例如:

3.字符串的其他操作
在MATLAB语言中,除了常用的字符串创建、比较、查找和替换操作外,还有许多其他字符串操作,如表2-4所示。
表2-4 字符串其他操作函数

例如:

2.5.3 字符串转换
在MATLAB语言中,字符串进行算术运算会自动转换为数值型。MATLAB还提供了许多字符串与数值之间的转换函数,如表2-5所示。
表2-5 字符串与数值转换函数

例如,可以利用字符串与数值之间的转换,对一串字符明文进行加密处理。MATLAB命令代码如下:
