Borrar filtros
Borrar filtros

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?

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Khushboo
Khushboo el 27 de Oct. de 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 comentarios
Stergios Verros
Stergios Verros el 27 de Oct. de 2022
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!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

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