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

4 visualizzazioni (ultimi 30 giorni)
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 Commenti
Srishti Saha
Srishti Saha il 7 Mag 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

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 7 Mag 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 Commenti
Stephen23
Stephen23 il 7 Mag 2018
Modificato: Stephen23 il 7 Mag 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by