Merge two lines where the first line has a space at the end of matlab

I am trying to concatenate two lines using:

str=strcat('Hello World ',char(hi)); 

where hi is 1x1 cell that has the string 'hi' .

But str looks like Hello Worldhi .

Why am I missing " "after Hello World ?

+5
source share
2 answers

Reason in strcat documentation :

To enter characters in an array, strcat deletes the final ASCII-white space characters: space, tab, vertical tab, new line, carriage return, and Form feed. Keep trailing spaces when concatenating character arrays, use concatenation of horizontal arrays, [s1, s2, ..., sN] .

To enter an array of cells, strcat does not remove the strcat white space.

So: either use the rows of the cells (create a cell containing the row)

 hi = {'hi'}; str = strcat({'Hello World '},hi) 

or simple, parenthesized concatenation (will result in a string):

 str = ['Hello World ',char(hi)] 
+4
source

I'm not quite sure why this comes from what was mentioned in the previous documentation answer, 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)); 
0
source

All Articles