narayana manohar
narayana manohar

Reputation: 21

Need to split string based on delimiters , but those are grouped

I have a string like

String str = "(3456,"hello", world, {ok{fub=100, fet = 400, sub="true"}, null }, got, cab[{m,r,t}{u,u,r,}{r,m,"null"}], {y,i,oft{f,f,f,f,}, tu, yu, iu}, null, null)

Now I need to split this string based on comma(,) but the strings which are between {} and [] should not be split. So my out put should look like

3456
hello
world
{ok{fub=100, fet = 400, sub="true"}, null}
got
cab[{m,r,t}{u,u,r,}{r,m,"null"}]
{y,i,oft{f,f,f,f,}, tu, yu, iu}
null
null

I know that it looks strange, I can do it by using old traditional brute force methods, but I need if there is any simplest logic for these kind of problems.

Can any one help me?

Thanks in advance :-)

Upvotes: 2

Views: 87

Answers (1)

M. Shaw
M. Shaw

Reputation: 1742

// Assuming open brackets have corresponding close brackets
int brackets = 0;
int currIndex = 0;
List<String> output = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
    if (isOpenBracket(str.charAt(i))) {
        brackets++;
    } else if (isCloseBracket(str.charAt(i))) {
        brackets--;
    } else if (str.charAt(i) == ',') {
        output.add(str.substring(currIndex, i));
        currIndex = i + 1;
    }
}
output.add(currIndex, str.length());
return output;

Would this work?

Upvotes: 2

Related Questions