How to invert parentheses?

I want to convert this () into this ) (

Like for example (1+2) to ) 1+2(

i have tried this

char[] cArray = text.ToCharArray();
        for (int i = 0; i < text.Length; i++)
        {
            if (cArray[i] == '(')
            {
                cArray[i] = ')';

            }
            if (cArray[i] == ')')
            {
                cArray[i] = '(';
            }
        }
        string p=new string(cArray);
        return p;

but it does not work

Jon Skeet
people
quotationmark

The problem is that after you've changed ( to ), the second if statement will immediately be true, so the character is flipped back again. The reverse isn't true though - if you start off with ) that will be flipped by the second statement, but then it won't be flipped back again. The net result is that all ) characters will be flipped to (, but that's all. So an input of "(((foo)))" would return "(((foo(((.

The simplest way to fix that is to use an else statement:

char[] cArray = text.ToCharArray();
for (int i = 0; i < text.Length; i++)
{
    if (cArray[i] == '(')
    {
        cArray[i] = ')';
    }
    else if (cArray[i] == ')')
    {
        cArray[i] = '(';
    }
}
return new string(cArray);

Alternatively, you could use a switch statement, which would be simpler if you had a lot of different cases to consider:

char[] cArray = text.ToCharArray();
for (int i = 0; i < text.Length; i++)
{
    switch (cArray[i])
    {
        case '(':
            cArray[i] = ')';
            break;
        case ')':
            cArray[i] = '(';
            break;
        // No need for a default as it would be a no-op
    }
}
return new string(cArray);

A switch statement will only evaluate the expression once (on each iteration, of course) so you don't need to worry about the two cases interfering with each other.

people

See more on this question at Stackoverflow