How can I take variable number of input strings in a function and return the concatenated output string?
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
Stephen23
on 7 May 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 Comments
Stephen23
on 7 May 2018
Edited: Stephen23
on 7 May 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.
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!