필터 지우기
필터 지우기

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 (최근 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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by