Advertisement
damarijsilva

ControlarParentizacion

Oct 2nd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Ejercicio7
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {            
  12.             String cadena;
  13.          
  14.             Console.WriteLine("Ingrese su operacion");
  15.             cadena = Console.ReadLine();
  16.  
  17.             if (ControlParentizacion(cadena, '(', ')') != 1)            
  18.                 Console.WriteLine("Parentesis mal parentizados");
  19.             else
  20.             {
  21.                 if (ControlParentizacion(cadena, '[', ']') != 1)
  22.                     Console.WriteLine("Corchetes mal parentizados");
  23.                 else
  24.                 {
  25.                     if (ControlParentizacion(cadena, '{', '}') != 1)
  26.                         Console.WriteLine("Llaves mal parentizadas");
  27.                     else
  28.                         Console.WriteLine("BIEN! parentizacion correcta!");
  29.                 }
  30.             }
  31.  
  32.             Console.ReadLine();
  33.  
  34.         }
  35.  
  36.  
  37.         public static int ControlParentizacion(string cadena, char abre, char cierra)
  38.         {
  39.             int i = 0;
  40.             int cont = 1;
  41.             Stack<object> caracteres = new Stack<object>();
  42.  
  43.             while(i<cadena.Length && cont == 1)
  44.             {
  45.                 char c = Convert.ToChar(cadena.Substring(i, 1));
  46.                 if (c == abre)
  47.                 {
  48.                     caracteres.Push(cadena.Substring(i, 1));
  49.                 }
  50.                 else
  51.                 {
  52.                     if (c==cierra)
  53.                     {                      
  54.                         if (caracteres.Count > 0)
  55.                         {
  56.                             caracteres.Pop();
  57.                         }
  58.                         else
  59.                         {
  60.                             cont = 0;
  61.                         }
  62.                     }
  63.                 }
  64.                 i++;
  65.             }
  66.  
  67.             if (cont == 1 && caracteres.Count > 0)
  68.                 cont = 0;
  69.             while (caracteres.Count > 0)
  70.             {
  71.                 caracteres.Pop();
  72.             }
  73.  
  74.             return cont;
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement