Simple Text Editor

  • + 0 comments
        static void Main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
            
            int q = int.Parse(Console.ReadLine().Trim());
            
            Editor editor = new Editor();
            
            for(int i = 0; i < q; i++){
                string[] op = Console.ReadLine().Trim().Split(' ');
                
                editor.Execute(int.Parse(op[0]), op.Length > 1 ? op[1] : null);
            }
        }
        
        public class Editor {
            public string Text = string.Empty;
            public Stack<string> Undos = new Stack<string>();
            
            private ITextOperation[] operations = {
                new AppendOperation(),
                new DeleteOperation(),
                new PrintOperation(),
                new UndoOperation()
            };
            
            public void Execute(int opId, string p){
                operations[opId - 1].Execute(this, p);
            }
            
        }
        
        public interface ITextOperation{
            public void Execute(Editor editor, string val);
        }
        
        public class AppendOperation : ITextOperation {
            public void Execute(Editor editor, string val){
                editor.Undos.Push(editor.Text);
                editor.Text += val;
            }
        }
        public class DeleteOperation : ITextOperation {
            public void Execute(Editor editor, string val){
                int k = int.Parse(val);
                editor.Undos.Push(editor.Text);
                editor.Text = editor.Text.Remove(editor.Text.Length - k);
            }
        }
        public class PrintOperation : ITextOperation {
            public void Execute(Editor editor, string val){
                int k = int.Parse(val);
                Console.WriteLine(editor.Text[k-1]);
            }
        }
        public class UndoOperation : ITextOperation {
            public void Execute(Editor editor, string val){
                editor.Text = editor.Undos.Pop();
            }
        }