Function for concatenating strings with delimiters?

123 ビュー (過去 30 日間)
sco1
sco1 2011 年 11 月 1 日
コメント済み: P Lepage 2020 年 11 月 11 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by