您的位置:首页 > 编程语言 > MATLAB

matlab:字符串数组和string的区别

2017-04-17 09:08 1071 查看

前言

在用sprintf()格式化输出时,发现formatSpec可以是单引号创建的字符串数组,也可以是string(‘str’)创建的string。所以产生了疑惑,这两者有什么区别,各适用在什么场合

官方文档

Character arrays and string arrays provide storage for text data in MATLAB®.

A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store short pieces of text as character vectors, such as c = 'Hello World'.

A string array is a container for pieces of text. String arrays provide a set of functions for working with text as data. Starting in R2017a, you can create strings using double quotes, such as str = "Greetings friend". To convert data to string arrays, use the string function.


代码

str=sprintf('pi = %.5f',pi);  %输出类型为char
str1=sprintf(string('pi = %.5f'),pi);    %输出类型为string


输出结果:

%测试字符串数组
>> class(str)
ans =
char

>> str(1)
ans =
p

>> size(str)
ans =
1    12

%测试string
>> class(str1)
ans =
string

>> size(str1)
ans =
1     1

>> str1(1)
ans =
string
"pi = 3.14159"


总结

由文档中可看出:

1. 字符串数组就相当于数据类型为char的矩阵(向量)。用单引号创建。可以索引。

2. string相当于一个类。用string()函数创建实例对象。所以有一些函数可以对string进行操作。size为1*1。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  matlab 格式化
相关文章推荐