How can I split string based on a sting array?

3 visualizaciones (últimos 30 días)
Stergios Verros
Stergios Verros el 14 de Sept. de 2022
Editada: Stergios Verros el 26 de Oct. de 2022
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

Respuesta aceptada

Stephen23
Stephen23 el 14 de Sept. de 2022
Editada: Stephen23 el 14 de Sept. de 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" "}"

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by