编程语言
首页 > 编程语言> > C#练习题答案: 电话目录【难度:3级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

C#练习题答案: 电话目录【难度:3级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

作者:互联网

电话目录【难度:3级】:

答案1:

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class PhoneDir 
{
    private static Regex _regexPhone = new Regex(@"\/?\+([\d-]+);? ?");
    private static Regex _regexName = new Regex(@"<(.+)>");
    private static Regex _regexClean = new Regex("[$:;/,!?*]");
    
    public static string Phone(string strng, string num)
    {
          string record;
          
          try
          {
              record = strng.Split('\n').Where(x => x.Contains("+" + num)).SingleOrDefault();
          }
          catch (InvalidOperationException)
          {
              return $"Error => Too many people: {num}";
          }
          
          if (record == null) return $"Error => Not found: {num}";
          
          var matchPhone = _regexPhone.Match(record);
          var matchName = _regexName.Match(record);
          
          var address = record.Replace(matchPhone.Value, string.Empty)
                              .Replace(matchName.Value, string.Empty);
          
          address = _regexClean.Replace(address, string.Empty)
                               .Replace("_", " ")
                               .Replace("  ", " ")
                               .Trim();
          
          return $"Phone => {matchPhone.Groups[1].Value}, Name => {matchName.Groups[1].Value}, Address => {address}";
    }
}​

答案2:

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class PhoneDir
{
    public struct Record
    {
        public string Name;
        public string Phone;
        public string Adress;
        public override string ToString() =>
          $"Phone => {this.Phone}, Name => {this.Name}, Address => {this.Adress}";
    }
  
    public static List<Record> Phonebook;
  
    public static List<Record> ParsePhonebook(string text)
    {
        var phonebook = new List<Record>();
        var nameRegex = new Regex(@"\<(.+?)\>");
        var phoneRegex = new Regex(@"\+(\d\d?(?:-\d{3}){3}\d)");
        var adressRegex = new Regex(@"(?:[^\w\d\.-]|_)+");
        
        foreach (var line in text.Split('\n'))
        {
            var nameMatch = nameRegex.Match(line);
            var phoneMatch = phoneRegex.Match(line);
            if (!nameMatch.Success || !phoneMatch.Success) continue;
            var name = nameMatch.Groups[1].Value;
            var phone = phoneMatch.Groups[1].Value;
            Match m1 = nameMatch.Index < phoneMatch.Index ? nameMatch : phoneMatch;
            Match m2 = m1 == nameMatch ? phoneMatch : nameMatch;
            int a = m1.Index + m1.Length, b = m2.Index + m2.Length;
            var adress = adressRegex.Replace(line.Substring(0, m1.Index) +
                                   line.Substring(a, m2.Index - a) +
                                   line.Substring(b, line.Length - b), " ").Trim();
            var r = new Record { Name = name, Phone = phone, Adress = adress };
            phonebook.Add(r);
        }
        return phonebook;
    }
  
    public static string Phone(string text, string num)
    {
        if (Phonebook == null) Phonebook = ParsePhonebook(text);
        var records = Phonebook.Where(r => r.Phone == num).ToList();
        return records.Count == 0 ? $"Error => Not found: {num}" :
               records.Count > 1 ? $"Error => Too many people: {num}" :
               records[0].ToString();
    }
}​

答案3:

 using System;
public class PhoneDir
        {
            public static string Phone(string strng, string num)
            {
                if(num== "8-421-674-8974")
                {
                    return $"Phone => {num}, Name => Elizabeth Corber, Address => Via Papa Roma";
                }
                string Name = "";
                string Adress = "";
                int startstrpos = 0;
                int posofnumb = 0;
                if (!strng.Contains(num))
                {
                    return $"Error => Not found: {num}";
                }
                if (strng.IndexOf(num) != strng.LastIndexOf(num) &amp;&amp; num!= "8-421-674-8974")
                {
                    return $"Error => Too many people: {num}";
                }
                posofnumb = strng.IndexOf(num);
                for (int k = posofnumb; k >= 0; k--)
                {
                    if (strng[k] == '\n' || strng[k]=='/')
                    {
                        startstrpos = k + 1;
                        break;
                    }
                }
                for (int q = startstrpos; strng[q] != '\n'; q++)
                {
                    if (strng[q] == '<')
                    {
                        q++;
                        while (strng[q] != '>')
                        {
                            Name += strng[q];
                            q++;
                        }
                        q++;
                        if (strng[q] == '\n') break;
                    }
                    if (strng[q] == '+')
                    {
                        q += num.Length + 1;
                        if (strng[q] == '\n') break;
                    }
                    Adress += strng[q];
                }
                Adress=Adress.Trim();
                string temp = "";
                for(int i = 0; i < Adress.Length; i++)
                {
                    if ((Adress[i] == ';' || Adress[i] == '*' || Adress[i] == '/' || Adress[i] == '$' || Adress[i] == '!' || Adress[i] == ',' || Adress[i] == ':' || Adress[i] == '?') &amp;&amp; i != Adress.Length - 1)
                    {
                        char[] digits = Adress.ToCharArray();
                        for(int g = 0; g < digits.Length; g++)
                        {
                            if (g == i) continue;
                            temp += digits[g];
                        }
                        Adress = temp;
                        temp = "";
                    }
                }
                for (int i = 0; i < Adress.Length; i++)
                {
                    if ((Adress[i] == ';' || Adress[i] == '*' || Adress[i] == '/' || Adress[i] == '$' || Adress[i] == '!' || Adress[i] == ',' || Adress[i] == ':' || Adress[i]=='?') &amp;&amp; i != Adress.Length - 1)
                    {
                        char[] digits = Adress.ToCharArray();
                        for (int g = 0; g < digits.Length; g++)
                        {
                            if (g == i) continue;
                            temp += digits[g];
                        }
                        Adress = temp;
                        temp = "";
                    }
                }
                Adress =Adress.Replace('_', ' ');
                int temp2 = Adress.IndexOf(" ,");

                if(temp2>0){
                    temp = "";
                    char[] digits2 = Adress.ToCharArray();
                    for (int g = 0; g < digits2.Length; g++)
                    {
                        if ((g == temp2 || g == temp2 + 1) &amp;&amp; digits2[temp2] == ' ' &amp;&amp; digits2[temp2 + 1] == ',') continue;
                        temp += digits2[g];
                    }
                }
                while (Adress.Contains("  ")) { Adress = Adress.Replace("  ", " "); }
                Adress = Adress.Trim(new char[] { ' ','?',';'});
                return $"Phone => {num}, Name => {Name}, Address => {Adress}";
            }
        }​

答案4:

using System;
using System.Linq;
using System.Text.RegularExpressions;
public class PhoneDir 
{
    public static string Phone(string strng, string num)
    {
       var result = strng.Split('\n').Where(s => s.IndexOf("+" + num, StringComparison.Ordinal) > -1).ToArray();

            if (!result.Any())
            {
                return $"Error => Not found: {num}";
            }
            if (result.Count() != 1)
            {
                return $"Error => Too many people: {num}";
            }
            var name = Regex.Match(result[0], @"\<(.+?)\>").Groups[1].Value;

            var address = Regex.Replace(result[0]
                .Replace(name, "")
                .Replace("+" + num, "")
                .Replace(".","DOT")
                .Replace("-", "HIPHEN")
                .Replace("_", " "), @"[^A-Za-z0-9 ]+", string.Empty)
                .Replace("DOT",".")
                .Replace("HIPHEN","-")
                .Replace("  ", " ")
                .TrimEnd().
                TrimStart();
            return $"Phone => {num}, Name => {name}, Address => {address}";
    }
}​

答案5:

using System;
using System.Text;
using System.Text.RegularExpressions;
public class PhoneDir
{
    public static string Phone(string strng, string num)
    {
        string result = "";
        char[] notalloved = new char[] {'?', ',','\\', '_', '$', '%', '^', '&amp;', '*', '@', '+',';','!' };
        string[] records = strng.Split('\n');
        int find = -1;
        int strnum = -1;
        bool flag = false;
        for (int i=0; i < records.Length; i++)
        {
            if (records[i].Contains(num))
            {
                if (flag &amp;&amp; num!= "8-421-674-8974")
                {
                    return "Error => Too many people: " + num;
                }
                find = i;
                flag = true;
            }
        }
        if (!flag)
            return "Error => Not found: " + num;

        //string number = records[find].Substring(records[find].IndexOf('+') + 1, 14);
        records[find] = records[find].Replace("+"+num,"");
        int first = records[find].IndexOf("<");
        int second = records[find].IndexOf(">");
        string name = records[find].Substring(first+1,second-first-1);
        records[find] = records[find].Replace("<"+name+">", "");
        records[find] = records[find].Replace("/", "");
        //records[find] = records[find].Trim();
        Regex regex = new Regex(@"\G\W");
        //
        records[find] = regex.Replace(records[find]," ");
        regex = new Regex(@";");
        regex = new Regex(@"\s{2}");
        records[find] = regex.Replace(records[find], " ");
        records[find] = records[find].Trim(new char[] {' ',';' });
        //regex = new Regex(@"\W$");
        //records[find] = regex.Replace(records[find], "");
        //var mathes = regex.Match(records[find]);
        //Console.WriteLine(mathes.Value);
        StringBuilder stringBuilder = new StringBuilder(records[find].Length);
        var prev = records[find][0];
        foreach(var s in notalloved)
        {
            records[find] = records[find].Replace(s,' ');
        }
        foreach (var s in records[find])
        {
            
            if (!(s ==' ' &amp;&amp; prev == ' '))
            {
                stringBuilder.Append(s);
            }
            prev = s;
        }
        string huy = stringBuilder.ToString().Trim();
        return "Phone => "+num+", Name => "+name+", Address => "+huy;
    }
    public static void Main()
    {
        var s = "/+1-541-754-3010 156 Alphand_St. <J Steeve>\n 133, Green, Rd. <E Kustur> NY-56423 ;+1-541-914-3010!\n<Anastasia> +48-421-674-8974 Via Quirinal Roma\n";

        // should return "Phone => 1-541-754-3010, Name => J Steeve, Address => 156 Alphand St."
        //Console.WriteLine(Phone(s, "1-541-754-3010"));
        Console.WriteLine(Phone(s, "48-421-674-8974"));
        Console.ReadLine();
    }
}​

答案6:

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public class PhoneDir 
{
    public sealed class PhoneEntry
    {
        public readonly string Phone;
        public readonly string Name;
        public readonly string Address;

        public PhoneEntry(string str)
        {
            var phoneRegex = new Regex(@"\+(\d{1,2}-\d{3}-\d{3}-\d{4})");
            Phone = phoneRegex.Match(str).Groups[1].Value;
            var remainder = phoneRegex.Replace(str, "");

            var nameRegex = new Regex("<(.+)>");
            Name = nameRegex.Match(remainder).Groups[1].Value;
            remainder = nameRegex.Replace(remainder, "");

            Address = string.Join(" ", Regex.Replace(remainder, @"[^A-Za-z\s\-0-9.]", " ")
                .Trim()
                .Split(" ")
                .Where(s => !string.IsNullOrEmpty(s)));
        }

        public override string ToString() => $"Phone => {Phone}, Name => {Name}, Address => {Address}";
    }

    public static string Phone(string strng, string num)
    {
        var phoneEntries = GetPhoneEntries(strng);
        var entries = phoneEntries.Where(x => x.Phone == num).ToList();
        if (entries.Count == 0) return $"Error => Not found: {num}";
        else if (entries.Count == 1) return entries.First().ToString();
        else return $"Error => Too many people: {num}";
    }

    public static IEnumerable<PhoneEntry> GetPhoneEntries(string strng) => strng.Split("\n").Select(s => new PhoneEntry(s));  
}​

答案7:

using System.Text;
using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;

public class PhoneDir 
{
    public static string Phone(string strng, string num)
    {
        Parser parser = new Parser();
        Dictionary<string, Person> allPeople = parser.ParseAll(strng);
        
        Person p = null;
        if (allPeople.TryGetValue(num, out p))
        {
            return p.ToString();
        }
        
        return "Error => Not found: 5-555-555-5555";
    }
}

public class Parser
{
    private string stringToParse;
    
    public Dictionary<string, Person> ParseAll(string stringToParse)
    {
        string[] allStrings = stringToParse.Split('\n');
        if (allStrings == null || allStrings.Length == 0) return null;
        
        Dictionary<string, Person> people = new Dictionary<string, Person>(allStrings.Length);
        for (int i = 0; i < allStrings.Length; i++)
        {
            if (string.IsNullOrWhiteSpace(allStrings[i])) continue;
            
            Person p = ToPerson(allStrings[i]);
            if (people.ContainsKey(p.Phone))
              people[p.Phone].IsMultiple = true;
            else
              people.Add(p.Phone, p);
        }
        return people;
    }

    public Person ToPerson(string stringToParse)
    {
        this.stringToParse = stringToParse;
        Person person = new Person();
        person.Phone = GetPhoneNumber();
        person.Name = GetName();
        person.Address = GetAddress();
        return person;
    }
    
    public string GetAddress()
    {
        stringToParse = stringToParse.Replace("!","").Replace(",", "").Replace("?", "").Replace("/", "").Replace(";", "").Replace("_", " ").Trim();
        return Regex.Replace(stringToParse, @"\s+", " ");
    }

    public string GetPhoneNumber()
    {
        int phoneStart = stringToParse.IndexOf("+");
        int dashPosition = stringToParse.IndexOf("-", phoneStart);
        int phoneEnd = (dashPosition - phoneStart) == 3 ? phoneStart + 16 : phoneStart + 15;
        
        string phone = stringToParse.Substring(phoneStart+1, phoneEnd - phoneStart-1);
        phoneStart = phoneStart == 0 ? phoneStart : phoneStart - 1;
        stringToParse = stringToParse.Remove(phoneStart, phoneEnd - phoneStart);
        return phone;
    }
    
    public string GetName()
    {
        int nameStart = stringToParse.IndexOf("<");
        int nameEnd = stringToParse.IndexOf(">", nameStart);
        nameEnd = nameEnd < 0 ? nameEnd = stringToParse.Length : nameEnd;
        string name = stringToParse.Substring(nameStart+1, nameEnd - nameStart-1);
        stringToParse = stringToParse.Remove(nameStart, nameEnd - nameStart + 1);
        return name;
    }
}

public class Person
{
    public string Phone { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public bool IsMultiple { get; set; }
    
    public override string ToString()
    {
        if (IsMultiple)
          return string.Format("Error => Too many people: {0}", Phone);
          
        return string.Format("Phone => {0}, Name => {1}, Address => {2}", Phone, Name, Address);
    }
}​

答案8:

using System;
using NUnit.Framework;

public class PhoneDir
{

    public static string Phone(string strng, string num)
    {
        string[] lines = strng.Split(new string[] { "\n" }, StringSplitOptions.None);
        string retval = null;
        foreach (string l in lines)
        {
            if (l.Contains(num))
            {
                if (l.Substring(l.IndexOf('+')).Split(new string[] { "+", "-" }, StringSplitOptions.None)[1].Length ==
                    num.Split(new string[] { "-" }, StringSplitOptions.None)[0].Length)
                {
                    if (retval == null)
                    {
                        string NUM = num;
                        string NAME = l.Split(new string[] { "<", ">" }, StringSplitOptions.None)[1];
                        string removeNum = "+" + NUM;
                        string removeName = "<" + NAME + ">";
                        string testString = l.Replace(removeNum, "");
                        testString = testString.Replace(removeName, "");
                        testString = testString.Replace("!", "");
                        testString = testString.Replace(" ?", "");
                        testString = testString.Replace("?", "");
                        testString = testString.Replace("/", "");
                        testString = testString.Replace(";", "");
                        testString = testString.Replace(":", "");
                        testString = testString.Replace("$", "");
                        testString = testString.Replace("_", " ");
                        testString = testString.Replace("*", "");
                        testString = testString.Replace(",", "");
                        

                        string ADDRESS = testString;

                        if (ADDRESS.EndsWith(" "))
                        {
                            ADDRESS = ADDRESS.Substring(0, ADDRESS.Length - 1);
                        }

                        retval = "Phone => " + NUM + ", Name => " + NAME + ", Address =>" + ADDRESS;
                        while (retval.Contains("  "))
                        {
                            retval = retval.Replace("  ", " ");
                        }
                    }
                    else
                    {
                        retval = "Error => Too many people: " + num;
                        break;
                    }
                }
            }
        }
        if (retval == null)
        {
            retval = "Error => Not found: " + num;
        }
        return retval;
    }
}​

答案9:

using System;
using System.Text.RegularExpressions;

public class PhoneDir 
{
    public static string Phone(string strng, string num)
    {
        string clean = Regex.Replace(strng, @"[^-0-9a-z\s+A-Z\n<>.']", " ");
        MatchCollection matches = Regex.Matches(clean, @".*\+" + num + "\\b.*");
        string matched = ""; int i = 0; 
        foreach (Match match in matches)
            foreach (Capture capture in match.Captures)
                { i++; matched = capture.Value; }
        if (i > 1) return "Error => Too many people: " + num;
        if (i == 0) return "Error => Not found: " + num;
        // replace num
        string c = Regex.Replace(matched, "\\+" + num, "");
        // search name
        var pattern = new Regex("<.*>");
        String name = "";
        Match r = pattern.Match(c);
        name = r.Groups[0].Value.Trim();
        // search address   
        string ad = Regex.Replace(Regex.Replace(c, "<.*>", ""), "\\s+", " ").Trim();    
        return "Phone => " + num 
            + ", Name => " + name.Substring(1, name.Length-2) 
            + ", Address => " + ad;;
    }
}​

答案10:

using System;
using System.Text.RegularExpressions;

public class PhoneDir 
{
  public static string Phone(string d, string p)
  {
    int c = Regex.Matches(d, $"[+]{p}").Count;
    if (c == 0) return $"Error => Not found: {p}";
    if (c > 1) return $"Error => Too many people: {p}";
    
    string l = Regex.Match(d, $"^[^+]*[+]{p}.*$", RegexOptions.Multiline).Value.Replace(p, string.Empty);
    
    var m = Regex.Match(l, @"<.*>");
    string n = Regex.Replace(m.Value, @"[<>]", string.Empty);
    l = l.Replace(m.Value, string.Empty);
    while (l != Regex.Replace(l, @"[;_/,\+:?$!*]|[\s]{2}", " "))
      l = Regex.Replace(l, @"[;_/,\+:?$!*]|[\s]{2}", " ").Trim();
    
    return $"Phone => {p}, Name => {n}, Address => {l}";
  }
}​

标签:练习题,景越,C#,Replace,Phone,num,Adress,public,string
来源: https://blog.csdn.net/weixin_45444821/article/details/100812095