How to insert space between strings while doing strcat ?

590 次查看(过去 30 天)
for eg: a='hello'; b='world'; strcat(a,b);
strcat(a,b) gives 'helloworld' But I need it as 'hello world' How can I do that ?

采纳的回答

Star Strider
Star Strider 2015-10-31
Use the square bracket [] concatenation operator, and including a space variable is the easiest way:
a='hello';
b='world';
s = ' ';
Result = [a,s,b]
Result =
hello world
  4 个评论
Giuseppe Degan Di Dieco
Thank you Star, you know, the most simple things are always underestimated, but actually the most difficult to found.
Best!

请先登录,再进行评论。

更多回答(4 个)

Hugh
Hugh 2017-11-21
I like to use the ASCII space character for this situation, code "32". for the OP: strcat(a,32,b) Extension: I would be inclined to also include a comma, code "44": strcat(a,44,32,b)
I look up the characters at: http://www.asciitable.com/

Walter Roberson
Walter Roberson 2018-5-5
There is a trick to strcat. Notice from the documentation,
"For character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form feed. For cell and string array inputs, strcat does not remove trailing white space."
This means that if you have
strcat(a, ' ', b)
then the "trailing" space of the ' ' input will be removed, which will have the effect of running the entries together. The trick is to use
strcat(a, {' '}, b)
  3 个评论
Walter Roberson
Walter Roberson 2019-2-6
a = {'hello';'bye'};
b = {'dolly';'louis'};
>> strcat(a, {' '}, b)
ans =
2×1 cell array
{'hello dolly'}
{'bye louis' }
No need to replicate the {' '}
Giuseppe Degan Di Dieco
Hello everybody,
all your solutions are brilliant, and lead to the same result.
Thanks for your help and time!

请先登录,再进行评论。


Stephen23
Stephen23 2015-11-1
编辑:Stephen23 2021-4-26
The most efficient approach is to use sprintf:
>> a = 'hello';
>> b = 'world!';
>> sprintf('%s %s',a,b)
hello world!

Larissa Bene
Larissa Bene 2018-5-5
strcat(string1, " "); strcat(string1, string2);
  2 个评论
Renwick Beattie
Renwick Beattie 2019-2-6
I get the following error on the " character
Error: The input character is not valid in MATLAB
statements or expressions.
Walter Roberson
Walter Roberson 2019-2-6
" is only valid in MATLAB from R2017a onwards. string() objects started existing in R2016b, but the input syntax of " was not enabled until R2017a.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by