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。
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值