How can I split a string in an array of strings such that each string is either a predefined array of strings, a variable or a string?

1 次查看(过去 30 天)
Hi all,
I have two predefined arrays, say:
first = ["alpha" "beta"];
second = ["{" "}"];
and I want to create a function which receives a string and splits the string in different string arrays(or cell). Each array(or cell) should contain either a single member of one of the two arrays, a variable that is not a member of the arrays (without including the blank space) or a string. Ex:
Input string:
"alpha{ beta} new {} new2 "This is a string" }"
Output string:
"alpha" "{" "beta" "new" "{" "}" "new2" "This is a string" "}"
In a previous post a Matlab member proposed this:
S = "alpha{ beta} new {} new2}";
T = ["alpha","beta", "{","}"];
[X,Y] = strsplit(S,T, 'CollapseDelimiters',false);
X = strtrim(X); % you forgot to mention, that you also want to remove whitespace
X(2,:) = [Y,""];
X(strlength(X)==0) = []
but this solution does not accept a string inside a string.
Hope it is clear!
Bests,
Stergios

采纳的回答

Khushboo
Khushboo 2022-10-27
Hello,
MATLAB accepts a string within a string only when the inner string is enclosed within single quotes and not double quotes. Keeping this in mind, I modified the previous MATLAB answer as mentioned by you to also include string within a string:
S = "alpha{ beta} new {} new2 'This is a string' }";
T = ["alpha","beta", "{","}", "'"]; %added "'" as a delimiter to detect string within a string
[X,Y] = strsplit(S,T, 'CollapseDelimiters',false);
Y = erase(Y, "'"); % removing all occurrences of "'" from result as it is not needed
X = strtrim(X); % you forgot to mention, that you also want to remove whitespace
X(2,:) = [Y,""];
X(strlength(X)==0) = [];
Thus the output for this is:
"alpha" "{" "beta" "}" "new" "{" "}" "new2" "This is a string" "}"

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by