strcat including space (i.e, ' ')
Ältere Kommentare anzeigen
I have to concatenate words, including spaces
Ex. a='word1'; b='word2';c=strcat(a,' ',b);
I need 'word1 word2', however, the value on c is 'word1word2'
Can you help me?
Akzeptierte Antwort
Weitere Antworten (4)
Paulo Silva
am 11 Jun. 2011
c=[a ' ' b]
strcat ignores trailing ASCII white space characters and omits all such characters from the output. White space characters in ASCII are space, newline, carriage return, tab, vertical tab, or form-feed characters, all of which return a true response from the MATLAB isspace function. Use the concatenation syntax [s1 s2 s3 ...] to preserve trailing spaces. strcat does not ignore inputs that are cell arrays of strings.
2 Kommentare
Daniel Foose
am 23 Feb. 2018
This is better than the accepted answer because it keeps the type the same. The accepted answer returns a cell with a string in it (which is different from a string). This answer returns a string.
Walter Roberson
am 23 Feb. 2018
The accepted answer returns a cell with a character vector in it. Strings did not exist in R2011a. If strings were being used then you would use a different approach:
>> a = "word1"; b = "word2"; a + " " + b
ans =
"word1 word2"
This requires R2017a or later. For R2016b,
>> a = string('word1'); b = string('word2'); a + ' ' + b
and before R2016b strings did not exist.
Jy·Li
am 25 Mai 2023
3 Stimmen
c=strcat(a,32,b); % the unicode value of ' ' is 32
Usman Nawaz
am 6 Sep. 2020
2 Stimmen
use double quotes instead of single quotes, worked for me.
1 Kommentar
Walter Roberson
am 6 Sep. 2020
That can be useful, but the output would be a string() object instead of a character vector. string() objects can be useful, but they need slightly different handling than character vectors.
string() objects became available in R2016b; using double-quotes to indicate string objects became available in R2017a.
R P
am 11 Jun. 2011
0 Stimmen
3 Kommentare
Paulo Silva
am 11 Jun. 2011
Please always test the answers provided before accepting them, Walter answer isn't correct (this time).
Walter Roberson
am 11 Jun. 2011
>> strcat({'word1'},{' '},{'word2'})
ans =
'word1 word2'
You can dereference this or cell2mat it if you want the string itself as output.
Jan
am 11 Jun. 2011
@Walter: CELL2MAT is not efficient here. S{1} is nicer.
Kategorien
Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!