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" "}"
  2 件のコメント
Stergios Verros
Stergios Verros 2022 年 10 月 27 日
Hi Khushboo,
I found one bug. If:
S = "alpha{ beta} new {} new2 new3 'This is a string' }";
The ouput will be:
"alpha" "{" "beta" "}" "new" "{" "}" "new2 new3" "This is a string" "}"
Is is possible to seperate the "new2 new3" to "new2" ''new3"?
Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by