matlab - 连接单元格字符串保持引用

时间:2015-09-11 22:09:53

标签: string matlab cell-array

假设我有一个字符串单元格如下:

ss = {'one', 'two', 'three'}

我想将这些字符串加入到1个字符串中。使用strjoin我得到了:

>> str = strjoin(ss, ', ')
str =
one, two, three

是否有任何简短的方法(1-2行代码)来保留所有引用',如下所示:

str = 'one', 'two', 'three'

2 个答案:

答案 0 :(得分:3)

尝试提供sprintf ss中包含的comma-separated list个字符串。在format specifier中,您可以包含引号,逗号和空格。最后需要删除最后一个逗号和空格。

result = sprintf('''%s'', ', ss{:}); %// cat the strings with quotes, comma and space
result = result(1:end-2); %// remove extra comma and space

答案 1 :(得分:2)

您可以在字符串的单元格数组上使用regular expressions在字符串之前和之后插入引号,然后在其上使用strjoin

ss = {'one', 'two', 'three'};
ss2 = regexprep(ss, '.+', '''$0''');
out = strjoin(ss2, ', ');

regexprep将一个匹配模式的单元格数组中的字符串替换为其他字符串。在这种情况下,我发现用模式.+收集整个单词,然后在单词之前和单词之后放置单引号。这是由''$0''完成的。每对''都是单引号。我用逗号分隔空格后加入字符串。

我们得到:

out =

'one', 'two', 'three'