NastySwipy

Regular Expressions (RegEx) - 04. Weather

May 23rd, 2018
1,035
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5.  
  6. namespace _10b_Regular_Expressions_RegEx_Exercises
  7. {
  8.     class Regular_Expressions_RegEx_Exercises
  9.     {
  10.       static void Main(string[] args)
  11.         {
  12.             string input = Console.ReadLine();
  13.             string pattern = @"(?<city>[A-Z]{2})(?<temperature>([\d]+)\.([\d]+))(?<weather>[A-Za-z]+)(\|)";
  14.             List<string> lines = new List<string>();
  15.  
  16.             while (input != "end")
  17.             {
  18.                 lines.Add(input);
  19.                 input = Console.ReadLine();
  20.             }
  21.  
  22.             List<Match> myMatches = new List<Match>();
  23.             foreach (var line in lines)
  24.             {
  25.                 MatchCollection m = Regex.Matches(line, pattern);
  26.                 foreach (Match thisMatch in m)
  27.                 {
  28.                     myMatches.Add(thisMatch);
  29.                 }
  30.             }
  31.  
  32.             Dictionary<string, List<string>> weather = new Dictionary<string, List<string>>();
  33.             foreach (Match current in myMatches)
  34.             {
  35.                 if (!weather.ContainsKey(current.Groups["city"].Value))
  36.                 {
  37.                     List<string> list = new List<string>();
  38.                     list.Add(current.Groups["temperature"].Value);
  39.                     list.Add(current.Groups["weather"].Value);
  40.                     weather.Add(current.Groups["city"].Value, list);
  41.                 }
  42.                 else
  43.                 {
  44.                     weather[current.Groups["city"].Value].Clear();
  45.                     weather[current.Groups["city"].Value].Add(current.Groups["temperature"].Value);
  46.                     weather[current.Groups["city"].Value].Add(current.Groups["weather"].Value);
  47.                 }
  48.             }
  49.             foreach (var pair in weather.OrderBy(x => double.Parse(x.Value[0])))
  50.             {
  51.                 Console.WriteLine($"{pair.Key} => {double.Parse(pair.Value[0]):F2} => {pair.Value[1]}");
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment