在编写程序的过程中,有很多场合我们需要拼接字符串,最常见的就是拼接文件路径,Matlab中常用的字符串拼接方法有三种,下面我们就来逐一介绍。
第一种方法:使用字符串数组
这种方法就是讲需要拼接的字符串按照顺序写成字符数组的形式,返回的就是数组中的元素拼接起来的字符串。
复制代码
1
2
3
4
5str1='I'; str2=' love'; str3=' you'; str4='!'; str = [str1,str2,str3,str4] %或者str = [str1 str2 str3 str4]
返回的字符串如下
复制代码
1
2
3str = I love you!
第二种方法:使用strcat函数
复制代码
1str = strcat(str1,str2,str3,str4)
返回的字符串为
复制代码
1
2
3str = I love you!
处了上述的使用方法,strcat还有另外两种常用的使用方式,请注意区分。
另外一:
复制代码
返回的字符串为
1str = strcat(['hello' ' world,'],[' hello' ' Matlab!'])
复制代码
1
2
3str = hello world, hello Matlab!
可以看到,该种方式是组合使用了字符串数组和strcat两种方式来拼接字符串。首先使用字符数拼接数组内的字符串,再将字符数据拼接后的字符串最为参数传递给strcat进行第二次拼接。
另外二:
复制代码
1str = strcat({'hello' ' world,'},{' hello' ' Matlab!'})
返回的字符串数组为
复制代码
1
2
3str = 'hello hello' ' world, Matlab!'
第三种方式:使用sprintf函数
复制代码
返回到字符串为
1
2
3num=10000; str = sprintf('%s%s%s%s%d%s%s',str1,str2,str3,' ',num,' years',str4)
复制代码
1
2
3str = I love you 10000 years!
最后
以上就是怕孤独手套最近收集整理的关于Matlab学习笔记(2)——拼接字符串的三种方式的全部内容,更多相关Matlab学习笔记(2)——拼接字符串内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复