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 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Stergios Verros
il 26 Ott 2022
Commentato: Stergios Verros
il 27 Ott 2022
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
0 Commenti
Risposta accettata
Khushboo
il 27 Ott 2022
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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!