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

6 vues (au cours des 30 derniers jours)
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 commentaires
Stephen23
Stephen23 le 7 Mai 2018
Modifié(e) : Stephen23 le 7 Mai 2018
@Srishti Saha: what have you tried so far? Is this your homework?
Srishti Saha
Srishti Saha le 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

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 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 commentaires
Stephen23
Stephen23 le 7 Mai 2018
Modifié(e) : Stephen23 le 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by