How can I split string based on a sting array?

3 visualizzazioni (ultimi 30 giorni)
Hi all,
I have two 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 or containing a string that is not a member of the arrays (without including the blank space). Ex:
Input string:
"alpha{ beta} new {} new2} "
Output string:
"alpha" "{" "beta" "new" "{" "}" "new2" "}"
I tried
[matches, non_matches] = strsplit("alpha{ beta} new {} new2}",[first second])
but first of all the outputs are seperated in matches and non_matches and second, the non_matches contain strings that are members of both arrays.
Hope that was clear!
Bests,
Stergios

Risposta accettata

Stephen23
Stephen23 il 14 Set 2022
Modificato: Stephen23 il 14 Set 2022
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) = []
X = 1×9 string array
"alpha" "{" "beta" "}" "new" "{" "}" "new2" "}"

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by