TheBulgarianWolf

Brackets format checker

Oct 11th, 2020
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Numerics;
  4.  
  5. namespace SoftuniExercisesWithVariables
  6. {
  7.     class Program
  8.     {
  9.         static bool isWellFormatted(string line)
  10.         {
  11.             Stack<char> lastOpen = new Stack<char>();
  12.             foreach (var c in line)
  13.             {
  14.                 switch (c)
  15.                 {
  16.                     case ')':
  17.                         if (lastOpen.Count == 0 || lastOpen.Pop() != '(') return false;
  18.                         break;
  19.                     case ']':
  20.                         if (lastOpen.Count == 0 || lastOpen.Pop() != '[') return false;
  21.                         break;
  22.                     case '}':
  23.                         if (lastOpen.Count == 0 || lastOpen.Pop() != '{') return false;
  24.                         break;
  25.                     case '(': lastOpen.Push(c); break;
  26.                     case '[': lastOpen.Push(c); break;
  27.                     case '{': lastOpen.Push(c); break;
  28.                 }
  29.             }
  30.             if (lastOpen.Count == 0) return true;
  31.             else return false;
  32.         }
  33.  
  34.         static void Main(string[] args)
  35.         {
  36.             Console.WriteLine("Enter your statement here: ");
  37.             string statement = Console.ReadLine();
  38.             bool check = isWellFormatted(statement);
  39.             if(check == true)
  40.             {
  41.                 Console.WriteLine("Your statement is well formatted.");
  42.             }
  43.             else
  44.             {
  45.                 Console.WriteLine("Your statement is not formatted right.");
  46.             }
  47.         }
  48.     }
  49. }
  50.  
Add Comment
Please, Sign In to add comment