From fc1ee1da6f9176f9db637ec21e5e5a18250b66d7 Mon Sep 17 00:00:00 2001 From: Lukasz Baldyga Date: Mon, 12 Oct 2020 12:47:12 +0100 Subject: [PATCH] Added Converters --- .../Converters.cs | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Advanced Software Engineering/Advanced Software Engineering/Converters.cs diff --git a/Advanced Software Engineering/Advanced Software Engineering/Converters.cs b/Advanced Software Engineering/Advanced Software Engineering/Converters.cs new file mode 100644 index 0000000..40ce015 --- /dev/null +++ b/Advanced Software Engineering/Advanced Software Engineering/Converters.cs @@ -0,0 +1,91 @@ +namespace Advanced_Software_Engineering +{ + public static class Converters + { + /// + /// This function removes spaces from the start and the end of the text. This should be unit tested. + /// + /// Simply any string of any size + /// A string without spaces at the begining or the end + /// + /// For example + /// + /// string a = " a simple sentence surrounded by spaces "; + /// string b = StripSpaces(a); + /// Console.WriteLine(b); // => "a simple sentence surrounded by spaces"; + /// + /// + /// + /// The code won't remove internal double spaces: + /// + /// string a = " a simple sentence surrounded by spaces "; + /// string b = StripSpaces(a); + /// Console.WriteLine(b); // => "a simple sentence surrounded by spaces"; + /// + /// + public static string Strip(string text) + { + int start; + + for (start = 0; start < text.Length; start++) + { + char character = text[start]; + if (character != " "[0]) break; + } + + int end; + + for (end = text.Length - 1; end >= 0; end--) + { + char character = text[end]; + if (character != " "[0]) break; + } + + return text.Substring(start, end); + + } + + public static int ConvertToInt(string text) + { + text = Strip(text); + return int.Parse(text); + } + + public static List StripStringArray(string[] array) + { + List newStringList = new List(); + + foreach (string arrayElement in array) + { + string strippedElement = Strip(arrayElement); + if (strippedElement.Length == 0) continue; + else newStringList.Add(strippedElement); + } + + return newStringList; + } + + public static Dictionary CommandAndParameterParser(string text) + { + Dictionary commandAndParameters = new Dictionary(); + + //split the command from the parameters + string[] parameters = Strip(text).Split(new char[] { " "[0] }, 2); + + //set command var + string command = Strip(parameters[0]); + commandAndParameters["command"] = new string[] { command }; + + //seperate all of the parameters by a comma + parameters = parameters[1].Split(","[0]); + + //Remove spaces around parameters + parameters = StripStringArray(parameters).ToArray(); + + //set parameter list + commandAndParameters["parameters"] = parameters; + + return commandAndParameters; + } + } +} \ No newline at end of file