How can I take variable number of input strings in a function and return the concatenated output string?

조회 수: 6 (최근 30일)
I have to write a function that takes variable number of inputs (even no input is allowed) and returns a concatenate string as the output.
Example: x1 = 'my'; x2= ' '; x3= 'holiday'; x4= ' '; x5= 'is'; x6= ' almost over!'; for all 6 input strings output would be= 'my holiday is almost over!';
if no input was passed, output should be empty
  댓글 수: 2
Stephen23
Stephen23 2018년 5월 7일
편집: Stephen23 2018년 5월 7일
@Srishti Saha: what have you tried so far? Is this your homework?
Srishti Saha
Srishti Saha 2018년 5월 7일
I have posted what I did. I just wanted to see if there is a better solution. you comment explains everything quite well. thanks.
This wasn't homework but a part of my end semester project

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 5월 7일
function out = myjoin(varargin);
out = sprintf(' %s',varargin{:});
out = out(2:end);
end
And tested:
>> myjoin()
ans =
>> myjoin('hello','world')
ans = hello world
  댓글 수: 3
Stephen23
Stephen23 2018년 5월 7일
편집: Stephen23 2018년 5월 7일
@Srishti Saha: expanding arrays in loops is not recommended, and the MATLAB editor shows a warning about doing this. Using ans as a variable name is not recommended, and also pointlessly spams the command window every time you call this function. However if you really just want to concatenate strings (without adding spaces in between) then the loop is not required anyway:
>> C = {'hello',' ','world'};
>> strcat(C{:})
ans = hello world
this will work for any number of string in the cell array C. You can put it in a function if you want:
function out = concatstrings(varargin)
out = strcat(varargin{:});
end
but personally I would not bother: they both require much the same calling syntax, and I do not see any advantage in writing/storing/maintaining this custom function when strcat does this already.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by