Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a string, holding ASCII characters. Find all name -> phone number pairs, format them and print them in an ordered list as list items.
- * The name should be at least one letter long, can contain only letters and should always start with an uppercase letter.
- * The phone number should be at least two digits long, should start and end with a digit (might also start with “+”) and might contain the following symbols in it: “(“, “)”, “/”, “.”, “-”, “ “ (left and right bracket, slash, dot, dash and whitespace).
- * Between a name and the phone number there might be any number of symbols, other than letters and “+”.
- * Between the name -> phone number pairs there might be any number of ASCII symbols.
- * The output format should be <b>[name]:</b> [phone number] (there is one space between the name and the phone number). Clear any characters other than digits and “+” from the number when printing the output.
- * The command "END" denotes the end of input.
- * The output should hold the resulting ordered list (on a single line), or a single paragraph, holding “No matches!” */
- namespace Phone_Numbers
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- class PhoneNumbers
- {
- static void Main(string[] args)
- {
- StringBuilder sb = new StringBuilder();
- string inputLine = Console.ReadLine();
- while (inputLine != "END")
- {
- sb.Append(inputLine);
- inputLine = Console.ReadLine();
- }
- Dictionary<string, string> contactList = new Dictionary<string, string>();
- FindAllNamePhoneNumberPairsInGivenText(sb.ToString(), contactList);
- PrintResults(contactList);
- }
- private static void FindAllNamePhoneNumberPairsInGivenText(string text, Dictionary<string, string> contactList)
- {
- const string pattern =
- @".*?([A-Z][A-Za-z]*)[^A-Za-z+]*?(\+?\d[\s\/)(.-]*\d[\d\s\/)(.-]*)";
- MatchCollection matches = Regex.Matches(text, pattern);
- foreach (Match match in matches)
- {
- string keyName = match.Groups[1].Value;
- string phoneNumber = match.Groups[2].Value.Trim();
- StringBuilder sb = new StringBuilder();
- foreach (char ch in phoneNumber.Where(ch => char.IsDigit(ch) || ch == '+'))
- {
- sb.Append(ch);
- }
- if (!contactList.ContainsKey(keyName))
- {
- contactList.Add(keyName, string.Empty);
- }
- contactList[keyName] = sb.ToString();
- }
- }
- private static void PrintResults(Dictionary<string, string> contactList)
- {
- if (contactList.Count == 0)
- {
- Console.WriteLine("<p>No matches!</p>");
- }
- else
- {
- Console.Write("<ol>");
- foreach (var contact in contactList)
- {
- Console.Write("<li><b>{0}:</b> {1}</li>",
- contact.Key, contact.Value);
- }
- Console.WriteLine("</ol>");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement