Function for concatenating strings with delimiters?

124 次查看(过去 30 天)
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!

采纳的回答

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

请先登录,再进行评论。

更多回答(2 个)

Matthew Eicholtz
Matthew Eicholtz 2015-9-6
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 2018-5-10
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'
>>

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by