Code Optimization

Interesting things about software development and code optimization

Split by comma but not inside of any parentheses or brackets

Hello friends,


If you are here then you in need of the same as me - split string by comma that is not inside of any brackets or parentheses.

So to do that you need the following piece of code (C# code):

string oval = "Home, Edit, HDMI (4K, ARC), Test, Double 2.0 x1, Multi (F1, (f2-f5, f6, 58), FF, o2), ARG";
string roval = "";
int isOpen = 0;
for (int i = 0i < oval.Lengthi++)
{
    if (isOpen <= 0 && oval[i] == ',')
    {
        roval += ",,";
    }
    else if (isOpen > 0 && (oval[i] == ')' || oval[i] == ']' || oval[i] == '}'))
    {
        isOpen--;
        roval += oval[i];
    }
    else if ((oval[i] == '(' || oval[i] == '[' || oval[i] == '{'))
    {
        isOpen++;
        roval += oval[i];
    }
    else
    {
        roval += oval[i];
    }
}

string[] split = roval.Split(",,"StringSplitOptions.RemoveEmptyEntries);


String you get to split looks like this: 

Home,, Edit,, HDMI (4K, ARC),, Test,, Double 2.0 x1,, Multi (F1, (f2-f5, f6, 58), FF, o2),, ARG

so you need just split it by double comma now.

This is fast, short and clear code that can be easily translated into any other language


Thank you and see you :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y