필터 지우기
필터 지우기

Function for concatenating strings with delimiters?

조회 수: 124 (최근 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 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