5

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 this Hello Worldhi.

Why am i missing a '' after Hello World?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Tak
  • 3,536
  • 11
  • 51
  • 93

2 Answers2

4

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)]
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • or use `sprintf ( '%s%s', str1, str2 )` which is very powerful and a lot faster! :) (And yes a little bit harder to read....) – matlabgui Apr 21 '15 at 16:16
0

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));
bilaly
  • 536
  • 3
  • 12