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

6 Ansichten (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 7 Mai 2018
Bearbeitet: Stephen23 am 7 Mai 2018
@Srishti Saha: what have you tried so far? Is this your homework?
Srishti Saha
Srishti Saha am 7 Mai 2018
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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 7 Mai 2018
function out = myjoin(varargin);
out = sprintf(' %s',varargin{:});
out = out(2:end);
end
And tested:
>> myjoin()
ans =
>> myjoin('hello','world')
ans = hello world
  3 Kommentare
Stephen23
Stephen23 am 7 Mai 2018
Bearbeitet: Stephen23 am 7 Mai 2018
@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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by