连接两个字符串,其中第一个字符串最后有一个 space Matlab
Concatenate two strings where first string has a space in the end Matlab
我正在尝试使用以下方法连接两个字符串:
str=strcat('Hello World ',char(hi));
其中 hi
是一个 1x1 cell
,它有字符串 'hi'
。
But str
appears like this Hello Worldhi
.
为什么我在 Hello World
之后缺少“
”?
For character array inputs, strcat
removes trailing ASCII white-space
characters: space, tab, vertical tab, newline, carriage return, and
form-feed. To preserve trailing spaces when concatenating character
arrays, use horizontal array concatenation, [s1, s2, ..., sN]
.
For cell array inputs, strcat
does not remove trailing white space.
因此:要么使用单元格字符串(将生成包含字符串的单元格)
hi = {'hi'};
str = strcat({'Hello World '},hi)
或普通的、基于括号的连接(将产生一个字符串):
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));
我正在尝试使用以下方法连接两个字符串:
str=strcat('Hello World ',char(hi));
其中 hi
是一个 1x1 cell
,它有字符串 'hi'
。
But
str
appears like thisHello Worldhi
.
为什么我在 Hello World
之后缺少“”?
For character array inputs,
strcat
removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form-feed. To preserve trailing spaces when concatenating character arrays, use horizontal array concatenation,[s1, s2, ..., sN]
.For cell array inputs,
strcat
does not remove trailing white space.
因此:要么使用单元格字符串(将生成包含字符串的单元格)
hi = {'hi'};
str = strcat({'Hello World '},hi)
或普通的、基于括号的连接(将产生一个字符串):
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));