Elements into a String

7 次查看(过去 30 天)
Dan Lynn
Dan Lynn 2015-10-12
评论: Stephen23 2015-10-12
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.

采纳的回答

Walter Roberson
Walter Roberson 2015-10-12
['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 个评论
Stephen23
Stephen23 2015-10-12
This code is only a partial solution. See my answer for a complete working solution.

请先登录,再进行评论。

更多回答(1 个)

Stephen23
Stephen23 2015-10-12
编辑:Stephen23 2015-10-12
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 个评论
Stephen23
Stephen23 2015-10-12
My pleasure. You can also vote for answers that are useful for you.

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by