String 连接两个字符串,其中第一个字符串的末尾有一个空格

String 连接两个字符串,其中第一个字符串的末尾有一个空格,string,matlab,cell-array,String,Matlab,Cell Array,我正在尝试使用以下命令连接两个字符串: str=strcat('Hello World ',char(hi)); 其中hi是一个1x1单元,其字符串为'hi' 但是str显示如下Hello Worldhi 为什么我在Hello World之后缺少一个“”?原因在于: 对于字符数组输入,strcat删除尾随的ASCII空白 字符:空格、制表符、垂直制表符、换行符、回车符和 表单提要。连接字符时保留尾随空格的步骤 数组,使用水平数组连接,[s1,s2,…,sN] 对于单元阵列输入,strcat不会

我正在尝试使用以下命令连接两个字符串:

str=strcat('Hello World ',char(hi));
其中
hi
是一个
1x1单元
,其字符串为
'hi'

但是
str
显示如下
Hello Worldhi

为什么我在
Hello World
之后缺少一个“
”?

原因在于:

对于字符数组输入,
strcat
删除尾随的ASCII空白 字符:空格、制表符、垂直制表符、换行符、回车符和 表单提要。连接字符时保留尾随空格的步骤 数组,使用水平数组连接,
[s1,s2,…,sN]

对于单元阵列输入,
strcat
不会删除尾随空格

所以:要么使用单元格字符串(将生成包含字符串的单元格)

或基于括号的普通连接(将生成字符串):


从前面关于文档的回答中,我不完全确定为什么会发生这种情况,但是下面的代码应该可以解决您的问题

%create two cells with the strings you wish to concatenate 
A = cell({'Hello World '});
B = cell({'hi'});

%concatenate the strings to form a single cell with the full string you
%want. and then optionally convert it to char in order to have the string
%directly as a variable.
str = char(strcat(A,B));
或者使用
sprintf('%s%s',str1,str2)
,它非常强大,而且速度更快(是的,读起来有点难……)
str = ['Hello World ',char(hi)]
%create two cells with the strings you wish to concatenate 
A = cell({'Hello World '});
B = cell({'hi'});

%concatenate the strings to form a single cell with the full string you
%want. and then optionally convert it to char in order to have the string
%directly as a variable.
str = char(strcat(A,B));