How to insert space between strings while doing strcat ?

조회 수: 584 (최근 30일)
Student S
Student S 2015년 10월 31일
댓글: Stephen23 2025년 1월 31일 5:43
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
Giuseppe Degan Di Dieco 2021년 4월 26일
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)
  댓글 수: 4
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco 2021년 4월 26일
Hello everybody,
all your solutions are brilliant, and lead to the same result.
Thanks for your help and time!
Paul Safier
Paul Safier 2025년 1월 30일 22:18
@Walter Roberson this is a nice way to do it.

댓글을 달려면 로그인하십시오.


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