1.7 字符串的表示与操作
1.字符串的表示
>> ch='asdgfgggggggghsfg';
>> subch=ch(1:5);
subch =
asdgf
>> revch=ch(end:-1:1);//倒置
revch =
gfshggggggggfgdsa
>> k=find(ch>='a'&ch<='z')
k =
Columns 1 through 12
1 2 3 4 5 6 7 8 9 10 11 12
Columns 13 through 17
13 14 15 16 17
>> ch(k)=ch(k)-('a'-'A')//小写改大写;用lower()和upper()更方便
ch =
ASDGFGGGGGGGGHSFG
>> length(k)
ans =
17
2.eval
>> t=pi;
>> m='[t,sin(t),cos(t)]';
>> y=eval(m)//将字符串当命令执行
y =
3.1416 0.0000 -1.0000
3.字符串和ASC码的转换
>> s1='MATLAB';
>> a=abs(s1);//abs函数将字符串变成ASC码
>> a
a =
77 65 84 76 65 66
>> char(a+32)//char将ASC码变成字符串
ans =
matlab
4.字符串的比较
>> 'www0'>='W123'
ans =
1 1 1 0
>> strcmp('www0','W123')
ans =
0
>> strncmp('www0','W123',1)//多了一个参数n代表前n个字符
ans =
0
>> strncmpi('www0','W123',1)//不管大小写
ans =
1
5.字符串查找
>> p=findstr('This is a test!','is')//短字符串在长字符串中的位置
p =
3 6
>> p=findstr('is','This is a test!')
p =
3 6
6.字符串替换
>> p=strrep('This is a test!','is','at')
p =
That at a test!