Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Tries to parse a string into a Room Type.
- /// </summary>
- /// <param name="s">String to parse</param>
- /// <param name="r">Returns the room result</param>
- /// <returns>If the parse was successful.</returns>
- public static bool TryParse(string s, out Room r)
- {
- // Used for empty rooms
- if (string.IsNullOrEmpty(s))
- {
- r = new Room(null);
- return true;
- }
- try
- {
- char dorm;
- int floor;
- int room;
- var stringCount = s.Length;
- if (stringCount >= 2 && stringCount <= 6)
- {
- string[] digits = new string[stringCount];
- for (int i = 0; i < stringCount; i++)
- {
- digits[i] = s.Substring(i, 1);
- }
- if (char.TryParse(digits[0], out dorm) && char.IsLetter(dorm)) // First letter
- {
- dorm = char.ToLower(dorm);
- int lengthToRoom = 0;
- string secondDigit = digits[1];
- if (secondDigit == "-" && stringCount < 5) // B-...
- {
- floor = 0;
- lengthToRoom = 2;
- }
- else if (int.TryParse(secondDigit, out floor)) // B0...
- {
- if (stringCount == 2)
- {
- floor = 0;
- lengthToRoom = 1;
- }
- else
- {
- string thirdDigit = digits[2];
- if (thirdDigit == "-" && stringCount < 6) // B0-...
- {
- lengthToRoom = 3;
- }
- else if (int.TryParse(thirdDigit, out floor)) // B00...
- {
- if (stringCount == 3)
- {
- floor = 0;
- lengthToRoom = 1;
- }
- else if (digits[3] == "-") // B00-...
- {
- lengthToRoom = 4;
- }
- else
- {
- throw new Exception("Invalid Input");
- }
- }
- else
- {
- throw new Exception("Invalid Input");
- }
- }
- }
- else
- {
- throw new Exception("Invalid Input");
- }
- // Solve last digits.
- var roomDigits = stringCount - lengthToRoom;
- if (!int.TryParse(s.Substring(lengthToRoom, roomDigits), out room))
- {
- throw new Exception("Invalid Input");
- }
- r = new Room(dorm, floor, room);
- return true;
- }
- else
- {
- throw new Exception("Invalid Input");
- }
- }
- }
- catch { }
- r = new Room('A', 0, 0);
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement