Search code examples
stringmatlabcell-array

Concatenate two strings where first string has a space in the end Matlab


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?


Solution

  • 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)]