Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invert parentheses?

Tags:

c#

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

like image 768
Rud Banisterloid Avatar asked Dec 02 '25 08:12

Rud Banisterloid


2 Answers

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.

like image 137
Jon Skeet Avatar answered Dec 04 '25 23:12

Jon Skeet


Use else before the second if as follows:

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

    }
    else if (cArray[i] == ')')
    {
        cArray[i] = '(';
    }
}
string p = new string(cArray);
return p;
like image 29
Dmitry Avatar answered Dec 04 '25 23:12

Dmitry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!