Reputation: 3616
I'm trying to concatenate two strings using:
str=strcat('Hello World ',char(hi));
where hi
is a 1x1 cell
which has the string 'hi'
.
But
str
appears like thisHello Worldhi
.
Why am i missing a '' after
Hello World
?
Upvotes: 5
Views: 1016
Reputation: 112679
The reason is in strcat
's documentation:
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.
So: either use cell strings (will produce a cell containing a string)
hi = {'hi'};
str = strcat({'Hello World '},hi)
or plain, bracket-based concatenation (will produce a string):
str = ['Hello World ',char(hi)]
Upvotes: 4
Reputation: 536
i'm not entirely sure why this is happening appart from what's mentioned in the previous answer about the documentation, but the following code should fix your problem.
%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));
Upvotes: 0