How to insert space between strings while doing strcat ?
Mostrar comentarios más antiguos
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 ?
Respuesta aceptada
Más respuestas (4)
Hugh
el 21 de Nov. de 2017
15 votos
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)
1 comentario
a='hello';
b='world';
strcat(a,44,32,b)
Walter Roberson
el 5 de Mayo de 2018
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 comentarios
Renwick Beattie
el 6 de Feb. de 2019
A note to say that if you are using strcat on multiple line cell arrays then the {' '} needs replicated to the same size of cell array (not character array) - e.g. cellstr(repmat({' '},size(a))) if a is the cell array.
Walter Roberson
el 6 de Feb. de 2019
a = {'hello';'bye'};
b = {'dolly';'louis'};
>> strcat(a, {' '}, b)
ans =
2×1 cell array
{'hello dolly'}
{'bye louis' }
No need to replicate the {' '}
Giuseppe Degan Di Dieco
el 26 de Abr. de 2021
Hello everybody,
all your solutions are brilliant, and lead to the same result.
Thanks for your help and time!
Paul Safier
el 30 de En. de 2025
@Walter Roberson this is a nice way to do it.
The most efficient approach is to use sprintf:
>> a = 'hello';
>> b = 'world!';
>> sprintf('%s %s',a,b)
hello world!
Larissa Bene
el 5 de Mayo de 2018
0 votos
strcat(string1, " "); strcat(string1, string2);
2 comentarios
Renwick Beattie
el 6 de Feb. de 2019
I get the following error on the " character
Error: The input character is not valid in MATLAB
statements or expressions.
Walter Roberson
el 6 de Feb. de 2019
" is only valid in MATLAB from R2017a onwards. string() objects started existing in R2016b, but the input syntax of " was not enabled until R2017a.
Categorías
Más información sobre Characters and Strings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!