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

前言

在用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。
发布了47 篇原创文章 · 获赞 33 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/kaever/article/details/70207486
今日推荐