Elements into a String

6 views (last 30 days)
Dan Lynn
Dan Lynn on 12 Oct 2015
Commented: Stephen23 on 12 Oct 2015
I have a two cell arrays, one consisting of food items to eat and another of what not to eat.
For example: C = {'ham', 'cheese', 'bread'} <--- food to eat and D = {'milk', 'apples', 'cherry'}
I need to put the items from both cell arrays into a string that is formatted like this:
'I can eat ham, cheese and/or bread, but do not eat milk, apples or cherry'
The number of elements in the cell arrays will not always be three; it is not consistent.
I am having trouble separating elements with commas and the last two items with an 'and/or' and 'or.'
There should not be a comma before the 'and/or' or the 'or.'
Also if there are only two items in a cell array then the output string should look lik this: 'I can eat ham and/or cheese, but do not eat milk or apples'
where there are no commas.

Accepted Answer

Walter Roberson
Walter Roberson on 12 Oct 2015
['I can eat ', strjoin(C(1:end-1), {', '}), ' and/or ', C{end}, ' but do not eat' .....]
You will need to modify this, however, for the case where there is only one item in the cell array.
  1 Comment
Stephen23
Stephen23 on 12 Oct 2015
This code is only a partial solution. See my answer for a complete working solution.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 12 Oct 2015
Edited: Stephen23 on 12 Oct 2015
C = {'ham', 'cheese', 'bread'};
D = {'milk', 'apples', 'cherries'};
X(2,:) = C;
Y(2,:) = D;
X(1,:) = {', '};
Y(1,:) = {', '};
X{1,end} = ' and/or ';
Y{1,end} = ' or ';
fmt = 'I can eat %s, but do not eat %s.';
out = sprintf(fmt,[X{2:end}],[Y{2:end}])
displays this in the command window:
out = I can eat ham, cheese and/or bread, but do not eat milk, apples or cherries.
And we can change the input arguments to check that it deals with the 'and/or' correctly:
D = {'cherries'};
... run the code again to produce this:
out = I can eat ham, cheese and/or bread, but do not eat cherries.
C = {'ham', 'cheese'};
... run the code again to produce this:
out = I can eat ham and/or cheese, but do not eat cherries.
C = {'ham'};
... run the code again to produce this:
out = I can eat ham, but do not eat cherries.
And it also expands nicely for longer lists too:
C = {'ham', 'cheese', 'bread', 'antelope', 'tofu', 'kimchi'};
D = {'apples'};
... run the code again to produce this:
out = I can eat ham, cheese, bread, antelope, tofu and/or kimchi, but do not eat apples.
  2 Comments
Dan Lynn
Dan Lynn on 12 Oct 2015
Thank you!
Stephen23
Stephen23 on 12 Oct 2015
My pleasure. You can also vote for answers that are useful for you.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!