Simple Text Editor

  • + 0 comments

    My C# solution

    class Solution {
        private enum Operation {
            Append,
            Delete
        }
        
        static void Main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
            
            var numberOfInputs = Int32.Parse(Console.ReadLine()!);
            var theString = string.Empty;
            var operations = new Stack<(Operation, string)>();
            
            for (var _ = 0; _ < numberOfInputs; _++)
            {
                var operation = Console.ReadLine()!.Split();
                
                switch (operation[0])
                {
                    case "1":
                        theString += operation[1];
                        operations.Push(new (Operation.Append, operation[1]));
                        continue;
                    case "2":
                        var k = Int32.Parse(operation[1]);
                        var stringToRemove = theString[(theString.Length - k)..];
                        theString = theString.Substring(0, theString.Length - k);
                        operations.Push(new (Operation.Delete, stringToRemove));
                        continue;
                    case "3":
                        k = Int32.Parse(operation[1]);
                        Console.WriteLine(theString[k - 1]);
                        continue; 
                    case "4":
                        var theOperation = operations.Pop();
                        if (theOperation.Item1 == Operation.Append)
                        {
                            theString = theString.Substring(0, theString.Length - theOperation.Item2.Length);
                            continue;
                        }
                        theString += theOperation.Item2;
                        continue;
                }
            }
        }
    }