C# method for checking a string

Asked

Viewed 116 times

1

Guys, someone there could give me a boost, help create this method in C#?

Method to check parentheses in a input. For example, the method should return verdadeiro for the following values:

((5+2)*2) + (40+20) + (((76-1)-3)*1)

So-and-so (the one who was at the bakery today ) looked for you.

And return Falso for the following values:

%:)

@:)

  • By "ASP.NET" you mean "C#", right?

  • Yes friend can help me?

  • 1

    It needs to be recursive anyway?

  • yes would have to be recursive.

1 answer

4


An ordinary solution would be:

String texto = "(()";

int parenteses = 0;
foreach (char c in texto)
{
    if (c.Equals('(')) {
        parenteses++;
    } else if (c.Equals(')')) {
        parenteses--;
    }

    if (parenteses < 0) {
        break;
    }
}

Console.WriteLine(parenteses == 0);

Testing

(() - FALSE

)( - FALSE

((1+1)*2) + (10+2) + ((((2-1)-1)*1) - TRUE

&:) - FALSE

Basically it checks if it started parentheses and makes control if it closed before, in case it closed it already interrupts the loop. It will only be correct if you closed all parentheses parenteses == 0

Ideone Demo

  • ")(" is a counterexample.

  • @ctgPi Adaptei :)

  • Other good test cases: "", "(", ")", "()", "()()", "(())".

  • @ctgPi I put the link to the ideone if you want to test, in all worked, but as the author of the question mentioned seems q he wants recursive and seems to me to be homework

  • 1

    I know they work. : ) I’m posting the test cases to the author of the same question. I don’t think it’s obvious that there’s a recursive solution that’s not just a crude way of doing the while of your solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.