Elements into a String

6 ビュー (過去 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 件のコメント
Dan Lynn
Dan Lynn 2015 年 10 月 12 日
Thank you!
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