Filter löschen
Filter löschen

Function for concatenating strings with delimiters?

124 Ansichten (letzte 30 Tage)
sco1
sco1 am 1 Nov. 2011
Kommentiert: P Lepage am 11 Nov. 2020
As the title says, I'm looking to concatenate character strings with a delimiter. For example, take 'sample','abc','1234','12' and combine them into 'sample_abc_1234_12'
I've written my own simple function for this, but I was just curious if there's a built-in function (similar to strcat) that accomplishes the same task.
Thanks!

Akzeptierte Antwort

Fangjun Jiang
Fangjun Jiang am 1 Nov. 2011
Something similar to this:
s={'sample','abc','1234','12'};
b=[sprintf('%s_',s{1:end-1}),s{end}]
  1 Kommentar
sco1
sco1 am 1 Nov. 2011
Ah, I knew I was forgetting something, I'm used to using fprintf and forgot about sprintf. Thanks!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Matthew Eicholtz
Matthew Eicholtz am 6 Sep. 2015
In case someone else stumbles upon this question like me, there is now a built-in function to accomplish this task:
s = {'sample','abc','1234','12'};
b = strjoin(s,'_');

Rishikesh Agrawani
Rishikesh Agrawani am 10 Mai 2018
strjoin() can be used to concatenate elements of cell array of character vectors.
>> cellArr = {'sample', 'abc', '1234', '12'};
>>
>> strjoin(cellArr, '_')
ans =
'sample_abc_1234_12'
>>
MATLAB - Use of datetime(), datestr(), strsplit(), strjoin()
>> now = datetime('now')
now =
datetime
10-May-2018 13:21:46
>> nowStr = datestr(datetime('now'))
nowStr =
'10-May-2018 13:22:33'
>> cellArr = nowStr.strsplit()
Struct contents reference from a non-struct array object.
>> cellArr = strsplit(nowStr) % split by ' '
cellArr =
1×2 cell array
'10-May-2018' '13:22:33'
>> % Concatenate all elements of cellArr
>> [cellArr{:}]
ans =
'10-May-201813:22:33'
>> % Join contents of cell array of character vectors by delimeter
>> strjoin(cellarr, '-')
Undefined function or variable 'cellarr'.
Did you mean:
>> strjoin(cellArr, '-')
ans =
'10-May-2018-13:22:33'
>> strjoin(cellArr, '_')
ans =
'10-May-2018_13:22:33'
>> strjoin(cellArr, '::')
ans =
'10-May-2018::13:22:33'
>> cellArr2 = {'This', 'is', 'a', 'great', 'opportunity', 'to', 'learn'}
cellArr2 =
1×7 cell array
'This' 'is' 'a' 'great' 'opportunity' 'to' 'learn'
>> strjoin(cellArr2, '-')
ans =
'This-is-a-great-opportunity-to-learn'
>>

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by