C#练习题答案: 市州【难度:2级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

市州【难度:2级】:

答案1:

using System.Linq;
using System.Collections.Generic;

public class State
{
    public static string ByState(string str)
    {       
        return string.Concat(str.Replace(",", "")
                            .Split('\n')
                            .GroupBy(x => GetState(x))
                            .OrderBy(x => x.Key)
                            .Select(x => GetPeopleWithState(states[x.Key], x.OrderBy(name => name))))
                            .Trim();  
    }
    
    private static string GetState(string str) => str.Split(' ').Last();
    
    private static string GetPeopleWithState(string state, IEnumerable<string> people)
    {
      return $" {state}\n" + string.Concat(people.Select(p => $"..... {p.Substring(0, p.Length-3)} {state}\n"));
    }
    
    private static Dictionary<string, string> states = new Dictionary<string, string>()
    {
      {"AZ", "Arizona"},
      {"CA", "California"},
      {"ID", "Idaho"},
      {"IN", "Indiana"},
      {"MA", "Massachusetts"},
      {"OK", "Oklahoma"},
      {"PA", "Pennsylvania"},
      {"VA", "Virginia"}    
    };
}

答案2:

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

public class State
{
    private class StateFriend:IComparable<StateFriend>
    {
        public String state;
        public String name;
        public String address;
        public String town;
        public int CompareTo(StateFriend other) {
            if (this.state.Equals(other.state)) {
                return this.name.CompareTo(other.name);
            }
            return this.state.CompareTo(other.state);
        }
    };
    public static string ByState(string str)
    {       
        string[] sa = new string[] {" MA", " VA", " OK", " PA", " CA", " AZ", " ID", " IN"};
        string[] st = new string[] {", Massachusetts", ", Virginia", ", Oklahoma", ", Pennsylvania", ", California", ", Arizona", ", Idaho", ", Indiana"};
        for (int i = 0; i < sa.Length; i++) {
            str = str.Replace(sa[i], st[i]);
        }
        string[] arr = Regex.Split(str, "[\\n]+").Where(s => s != string.Empty).ToArray<string>();
        List<StateFriend> narr = new List<StateFriend>();
        for (int i = 0; i < arr.Length; i++) {
            string[] y = Regex.Split(arr[i], ", ").Where(s => s != string.Empty).ToArray<string>();
            StateFriend sf = new StateFriend();
            sf.state = y[3].Trim();
            sf.name = y[0];
            sf.address = y[1];
            sf.town = y[2];
            narr.Add(sf);
        }
        narr.Sort((StateFriend c1, StateFriend c2) => c1.CompareTo(c2));
        string result = ""; string last = "";
        foreach (StateFriend sf in narr) {
            string e = sf.state;
            if (!e.Equals(last)) {
                last = e;
                result += "\n" + " " + e + "\n..... " + sf.name + " " + sf.address + " " + sf.town + " " + sf.state;
            } else {
                result += "\n..... " + sf.name + " " + sf.address + " " + sf.town + " " + sf.state;
            }
        }
        return result.Substring(2, result.Length - 2);
    }
}

答案3:

using System.Linq;
using System.Collections.Generic;
public class State
{
    static Dictionary<string, string> d = new Dictionary<string, string> { {"AZ", "Arizona"}, {"CA", "California"}, 
        {"ID", "Idaho"}, {"IN", "Indiana"}, {"MA", "Massachusetts"}, {"OK", "Oklahoma"}, {"PA", "Pennsylvania"}, {"VA", "Virginia"} };
    
    public static string ByState(string str) => string.Join("\n ", str.Split("\n").GroupBy(x => d[x.Substring(x.Length-2)]).OrderBy(g => g.Key)
        .Select(g => g.Key + string.Concat(g.Select(x => $"\n..... {x.Substring(0, x.Length-3).Replace(",","")} {g.Key}").OrderBy(x=>x))));
}

答案4:

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

public class State
{
    public static string ByState(string str)
    {
        var sb = new StringBuilder();

        var groupped = str.Split("\n", StringSplitOptions.RemoveEmptyEntries)
            .Select(l => Person.Parse(l))
            .OrderBy(p => p.State)
            .ThenBy(p => p.Name)
            .GroupBy(p => p.State);

        foreach (var g in groupped)
        {
            if (sb.Length != 0)
                sb.Append(' ');
            sb.AppendLine(g.Key);

            foreach (var p in g)
            {
                sb.AppendLine($"..... {p.Name} {p.Address} {p.City} {p.State}");
            }
        }
        return sb.ToString().TrimEnd();
    }
}

class Person
{
    enum Field
    {
        Name = 0,
        Address = 1,
        City = 2
    }

    static Dictionary<string, string> states = new Dictionary<string, string>()
        {
            { "AZ", "Arizona"},
            { "CA", "California"},
            { "ID", "Idaho"},
            { "IN", "Indiana"},
            { "MA", "Massachusetts"},
            { "OK", "Oklahoma"},
            { "PA", "Pennsylvania"},
            { "VA", "Virginia"}
        };

    public string Name;
    public string Address;
    public string City;
    public string State;

    public static Person Parse(string value)
    {
        var p = new Person();
        var fields = value.Split(", ");

        p.Name = fields[(int)Field.Name];
        p.Address = fields[(int)Field.Address];
        p.City = fields[(int)Field.City].Substring(0, fields[(int)Field.City].LastIndexOf(' '));
        p.State = states[fields[(int)Field.City].Substring(fields[(int)Field.City].LastIndexOf(' ') + 1)];

        return p;
    }
}

答案5:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

public class State
{
    public static string ByState(string input)
    {       
        var statesContainingFriends = new List<string>();
        var states = new Dictionary<string, string>()
        {
            ["AZ"] = "Arizona",
            ["CA"] = "California",
            ["ID"] = "Idaho",
            ["IN"] = "Indiana",
            ["MA"] = "Massachusetts",
            ["OK"] = "Oklahoma",
            ["PA"] = "Pennsylvania",
            ["VA"] = "Virginia"
        };

        input = input.Trim();
        foreach (var state in states)
        {
            if (input.Contains(state.Key))
            {
                input = input.Replace(state.Key, state.Value);
                statesContainingFriends.Add(state.Value);
            }
        }

        var output = "";
        foreach (var stateContainingFriends in statesContainingFriends)
        {
            output += $" {stateContainingFriends}\n";
            foreach (var line in input.Split("\n").OrderBy(x => x))
            {
                if (line.Contains(stateContainingFriends))
                output += $"..... {line}\n";
            }
        }

        output = output.Replace(",", "").Remove(0, 1);
        return output.Substring(0, output.Length-1);
    }
}

答案6:

using System;
using System.Collections.Generic;
using System.Linq;

public class State
{  
    private static readonly Dictionary<string, string> StateMappings = new Dictionary<string, string>
    {
        {"AZ", "Arizona"},
        {"CA", "California"},
        {"ID", "Idaho"},
        {"IN", "Indiana"},
        {"MA", "Massachusetts"},
        {"OK", "Oklahoma"},
        {"PA", "Pennsylvania"},
        {"VA", "Virginia"}
    };
    
    public static string ByState(string str)
    {
        return string.Join("\n", str.Split("\n")
                .GroupBy(x => x.Substring(x.Length - 2), x => x)
                .OrderBy(x => x.Key).ToDictionary(c => c.Key, c => c.ToList())
                .Select((x, i) =>
                    $" {StateMappings[x.Key]}" +
                    $"\n..... " +
                    $"{string.Join("\n..... ", x.Value.OrderBy(g => g)).Replace(x.Key, StateMappings[x.Key])}"))
            .Replace(",", "")
            .TrimStart();
    }
}

答案7:

using System;
using System.Collections.Generic;
using System.Linq;

public class State
{

    public static string ByState(string str)
    {   
  var states = new Dictionary<string,string>(){
           { "AZ","Arizona"},
           { "CA","California"},
           { "ID","Idaho"},
           { "IN","Indiana"},
           { "MA","Massachusetts"},
           { "OK","Oklahoma"},
           { "PA","Pennsylvania"},
           { "VA","Virginia"}
        };
        
        var rows = str.Split(new string[] {"\n"}, StringSplitOptions.RemoveEmptyEntries).Select(r=>{
           var state = states.FirstOrDefault(s=> r.Contains(s.Key));
           var row = r.Replace(",","").Replace(state.Key,state.Value);
            
           return new {
              State = state.Value,
              Row = row.Trim()
             };
        }).OrderBy(i=>i.State);
        
        var result = rows.GroupBy(r=>r.State).Select(i=> i.Key + "\n..... " + string.Join("\n..... ",i.Select(e=>e.Row).OrderBy(e=>e)));
        
        return string.Join("\n ",result);
    }
}

答案8:

using System;
using System.Collections.Generic;
using System.Linq;

public class State
{
    private static readonly Dictionary<string, string> StateNames = new Dictionary<string, string>()
    {
        { "AZ", "Arizona" }, { "CA", "California" }, { "ID", "Idaho" }, { "IN", "Indiana" }, { "MA", "Massachusetts" }, { "OK", "Oklahoma" }, { "PA", "Pennsylvania" }, { "VA", "Virginia" }
    };

    private class AddressEntry
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string StateName { get => StateNames[State]; }
    }

    public static string ByState(string str)
    {
        // Throw out invalid input
        if (string.IsNullOrWhiteSpace(str)) return string.Empty;

        // Parse the string into a list of address entries
        var addressBook = new List<AddressEntry>();
        var records = str.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var record in records)
        {
            var parts = record.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
            var city = parts[2].Substring(0, parts[2].Length - 3);
            var state = parts[2].Substring(parts[2].Length - 2, 2);
            var entry = new AddressEntry() { Name = parts[0], Address = parts[1], City = city, State = state };
            addressBook.Add(entry);
        }

        // Build the output formatted appropriately
        var list = new List<string>();
        foreach (var group in addressBook.GroupBy(e => e.StateName).OrderBy(g => g.Key))
        {
            list.Add($" {group.Key}");
            foreach (var entry in group.OrderBy(e => e.Name))
            {
                list.Add($"..... {entry.Name} {entry.Address} {entry.City} {entry.StateName}");
            }
        }
        return string.Join("\n", list).Substring(1);
    }
}

答案9:

using System;
using System.Collections.Generic;
using System.Linq;

public class State
{
    public static string ByState(string str)
    {       
        Dictionary<string, string> States = new Dictionary<string, string>()
            {
                { "AZ", "Arizona" },
                { "CA", "California"},
                { "ID", "Idaho"},
                { "IN", "Indiana" },
                { "MA", "Massachusetts" },
                { "OK", "Oklahoma" },
                { "PA", "Pennsylvania" },
                { "VA", "Virginia" }
            };
            Dictionary<string, List<string>> output = new Dictionary<string, List<string>>()
            {
                { "AZ", new List<string>() },
                { "CA", new List<string>() },
                { "ID", new List<string>() },
                { "IN", new List<string>() },
                { "VA", new List<string>() },
                { "OK", new List<string>() },
                { "PA", new List<string>() },
                { "MA", new List<string>() }
            };

            var arr = str.Split('\n');
            foreach (string ss in arr)
            {
                foreach (KeyValuePair<string, List<string>> state in output)
                {
                    if (ss.Contains(state.Key))
                    {
                        output[state.Key].Add(ss.Replace(state.Key, States[state.Key]));
                        break;
                    }
                }
            }
            var prepare = "";

            foreach (var elem in output.OrderBy(x => x.Key))
            {
                if (elem.Value.Count != 0)
                {
                    prepare += (prepare != ""? " ": "") + States[elem.Key] + "\n";
                    foreach(var people in elem.Value.OrderBy(z => z.Split(',')[0]).ThenBy(z => z.Split(',')[1]).ThenBy(z => z.Split(',')[2]).ToList())
                    {
                        prepare += "..... " + people.Replace(",", string.Empty) + "\n";
                    }
                }
            }
            return prepare.Substring(0, prepare.Length - 1);
    }
}

答案10:

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

public class State
{
    public static string ByState(string str)
    {       
       List<string> stringList1 = str.Split(new string[] { "\n" }, StringSplitOptions.None).OrderBy(s => s.Substring(s.Length - 2, 2)).ToList();
       var novaGrupiranaLista = stringList1.GroupBy(s => s.Substring(s.Length-2,2));

       string output = "";
       int counter =0;

       foreach (var group in novaGrupiranaLista)
            {
                string state="";
                counter++;

                switch (group.Key)
                {
                    case "AZ":
                        state = "Arizona";
                        break;
                    case "CA":
                        state = "California";
                        break;
                    case "ID":
                        state = "Idaho";
                        break;
                    case "IN":
                        state = "Indiana";
                        break;
                    case "MA":
                        state = "Massachusetts";
                        break;
                    case "OK":
                        state = "Oklahoma";
                        break;
                    case "PA":
                        state = "Pennsylvania";
                        break;
                    case "VA":
                        state = "Virginia";
                        break;
                }

                string space = "";

                if (counter!=1)
                {
                    space = " ";
                }

                output = output + space+state+ "\n";


                foreach (var item in group.OrderBy(s=> s))
                {
                    output=output+"..... "+item.Substring(0,item.Length-3)+" "+ state+"\n";
                }

            }

            output = output.TrimEnd(new char[] { '\n' }).Replace(",", "");                               

            return output; 
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值