Function for concatenating strings with delimiters?

91 vues (au cours des 30 derniers jours)
sco1
sco1 le 1 Nov 2011
Commenté : P Lepage le 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!

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (2)

Matthew Eicholtz
Matthew Eicholtz le 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 le 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'
>>

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by