C # method to check a string

1

Well, could anyone here give me a boost by helping to create this method in C #?

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

  

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

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

And return Falso for the following values:

  

%:)

     

@:)

    
asked by anonymous 16.06.2015 / 23:00

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);

Tests

  

(() - 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, if closed it already interrupts the loop. It will only be correct if you closed all parentheses parenteses == 0

Ideone Demo

    
16.06.2015 / 23:21