scmg
scmg

Reputation: 1894

matlab - join cell strings keeping quotations

Assuming I have a cell of strings as follows:

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

And I want to join these strings into 1 string. Use strjoin I got:

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

Is there any short way (1 - 2 lines of code) to keep all quotations ', as follows:

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

Upvotes: 1

Views: 148

Answers (2)

rayryeng
rayryeng

Reputation: 104545

You can perhaps use regular expressions on your cell array of strings to insert a quotation before and after the string, then use strjoin on that:

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

regexprep replaces strings in a cell array that match a pattern with something else. In this case, I'm finding collecting the entire word with pattern .+ then placing a single quotation before the word and after the word. That is accomplished by ''$0''. Each pair of '' is a single quotation. I join the strings after by a comma separated by spaces.

We get:

out =

'one', 'two', 'three'

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112749

Try supplying sprintf a comma-separated list of the strings contained in ss. In the format specifier you can include the quotation marks, comma and space. The last comma and space need to be removed at the end.

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

Upvotes: 3

Related Questions