C#练习题答案: 排序书名:忽略文章【难度:2级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

排序书名:忽略文章【难度:2级】:

答案1:

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

namespace Kata
{
  public class TitleSorter
  {
    private string IgnoreArticles(string x) {
      string output;
      if(x.StartsWith("A ") && x.Length > 2) {
        output = x.Substring(2) + ", A";
      } else if(x.StartsWith("An ") && x.Length > 3) {
        output = x.Substring(3) + ", An";
      } else if(x.StartsWith("The ") && x.Length > 4) {
        output = x.Substring(4) + ", The";
      } else {
        output = x;
      }
      return output;
    }
    public List<string> Sort(List<string> unsortedTitles)
    {
      if(unsortedTitles == null) {
        return null;
      }
      var output = unsortedTitles;
      output.Sort(delegate(string x, string y) {
        return IgnoreArticles(x).CompareTo(IgnoreArticles(y));
      });
      return output;
    }
  }
}

答案2:

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

namespace Kata
{
  public class TitleSorter
  {
    public List<string> Sort(List<string> unsortedTitles)
    {
      return unsortedTitles?.OrderBy(SortKey).ToList();
    }
    
    static readonly Regex SortKeyRe = new Regex(@"\A(The|An?)\s+(.+)\z");
    static string SortKey(string s) => SortKeyRe.Replace(s, "$2, $1");
  }
}

答案3:

using System;
using System.Collections.Generic;

namespace Kata
{
  public class TitleSorter
  {
    public List<string> Sort(List<string> unsortedTitles)
    {
      if(null == unsortedTitles){return null;}
      if(unsortedTitles.Count ==0 ) {return unsortedTitles;}
            
      for(int i=0; i<unsortedTitles.Count; i++)
      {
        string title  = unsortedTitles[i];
        if(String.IsNullOrEmpty(title) || title.Length == 1 ){ continue;}
        
        int firstSpace = title.IndexOf(" ");
        if(firstSpace == -1 || firstSpace > 3){continue;}        
        string part1 = title.Substring(0, firstSpace+1);
        int reminder = title.Length - firstSpace+1;
        string part2 = reminder>0? title.Substring(firstSpace+1):string.Empty;        
        
        if(string.Compare(part1.ToUpper(), "A ") == 0 ||
            string.Compare(part1.ToUpper(), "AN ") == 0 ||
            string.Compare(part1.ToUpper(), "THE ") == 0 )
        {
        if(String.IsNullOrEmpty(part2.Trim())){continue;}
          unsortedTitles[i] = part2+" , "+part1;
        }
      }
      
      unsortedTitles.Sort();
      
      for(int i=0; i<unsortedTitles.Count; i++)
      {
        string title  = unsortedTitles[i];
        if(String.IsNullOrEmpty(title) || title.Length == 1 ){ continue;}
        int LastComma = title.LastIndexOf(" , ");
        if(LastComma == -1 || LastComma+3 >= title.Length ){continue;}  
        string part1 = title.Substring(0, LastComma);
        string part2 = title.Substring(LastComma+3);
        
        unsortedTitles[i] = part2+part1;
      }      
      
      return unsortedTitles;
    }
  }
}

答案4:

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

namespace Kata
{
  public class TitleSorter
  {
    public List<string> Sort(List<string> unsortedTitles)
    {
      return unsortedTitles?.OrderBy(x=>Regex.Replace(x,@"(?i)^(the|an|a) (?!$)","")).ThenBy(x=>x.Length).ToList();
    }
  }
}

答案5:

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

namespace Kata
{
  public class TitleSorter
  {
    public List<string> Sort(List<string> unsortedTitles)
    {
      if (unsortedTitles == null) return null;
      Dictionary<string, string> titles = new Dictionary<string, string>();
      foreach (string title in unsortedTitles)
      {
        if (title.StartsWith("A ") &amp;&amp; title.Length > 2) titles.Add(title, title.Remove(0, 2) + ", A");
        else if (title.StartsWith("The ") &amp;&amp; title.Length > 4) titles.Add(title, title.Remove(0, 4) + ", The");
        else if (title.StartsWith("An ") &amp;&amp; title.Length > 3) titles.Add(title, title.Remove(0, 3) + ", An");
        else titles.Add(title, title);
      }
      return (from pair in titles orderby pair.Value select pair.Key).ToList();
    }
  }
}

答案6:

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

namespace Kata
{
  public class TitleSorter
  {
    private const string WordSeperator = " ";
    private const string ArticleSeperator = ", ";
    private static readonly string[] Articles = { "the", "an", "a" };
    
    public List<string> Sort(List<string> unsortedTitles)
    {
        return unsortedTitles?.OrderBy(GetSortableTitle).ToList();
    }

    private static string GetSortableTitle(string title)
    {
        var titleParts = title.Split(' ');
        return IsArticle(titleParts.First()) ? string.Join(WordSeperator, titleParts.Skip(1)) + ArticleSeperator + titleParts.First() : title;
    }
    
    private static bool IsArticle(string word)
    {
        return Articles.Contains(word.ToLower());
    }
  }
}

答案7:

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

namespace Kata
{
   public class TitleSorter
    {
        private static string[] Articles = { "the", "an", "a" };
        private const string ArtSep = ", ";
        private const string Seperator = " ";

        private static bool IsTypeOfArticle(string str)
        {
            return Articles.Contains(str.ToLower());
        }

        private static string GoSort(string inputTitle)
        {
            var parts = inputTitle.Split(' ');
            return IsTypeOfArticle(parts.First()) ? string.Join(Seperator, parts.Skip(1)) + ArtSep + parts.First() : inputTitle;
        }
        public List<string> Sort(List<string> commonTitles)
        {
            return commonTitles?.OrderBy(GoSort).ToList();
        }


       
    }
}

答案8:

using System;
using System.Collections.Generic;

namespace Kata
{
  public class TitleSorter
  {
        public List<string> Sort(List<string> unsortedTitles)
        {
            if (unsortedTitles == null) { return null;}
            List<string> sorted = new List<string>();
            for (int i = 0; i <unsortedTitles.Count; i++)
            {
                if (unsortedTitles[i].Contains("A ")  &amp;&amp; !(unsortedTitles[i].Contains(" A ") || unsortedTitles[i].Contains(" a ") || unsortedTitles[i] == "A "))
                {
                    unsortedTitles[i] = unsortedTitles[i].Remove(0, 2) + ", AA";
                }
                else if (unsortedTitles[i].Contains("The ") &amp;&amp; !(unsortedTitles[i].Contains(" The ") || unsortedTitles[i].Contains(" the ") || unsortedTitles[i] == "The "))
                {
                    unsortedTitles[i] = unsortedTitles[i].Remove(0, 4) + ", The";
                }
                else if (unsortedTitles[i].Contains("An ") &amp;&amp; !(unsortedTitles[i].Contains(" An ") || unsortedTitles[i].Contains(" an ") || unsortedTitles[i] == "An "))
                {
                    unsortedTitles[i] = unsortedTitles[i].Remove(0, 3) + ", An";
                }
            }

            unsortedTitles.Sort();
            sorted = unsortedTitles;
            for (int i = 0; i < sorted.Count; i++)
            {
                if (sorted[i].Contains(", AA"))
                {
                    sorted[i] = "A "+ sorted[i].Remove(sorted[i].Length - 4);
                }
                else if (sorted[i].Contains(", The"))
                {
                    sorted[i] = "The "+ sorted[i].Remove(sorted[i].Length - 5);
                }
                else if (sorted[i].Contains(", An"))
                {
                    sorted[i] = "An "+ sorted[i].Remove(sorted[i].Length - 4);
                }
            }
            

            return sorted;
        }
  }
}

答案9:

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

namespace Kata
{
  public class TitleSorter
  {
    public List<string> Sort(List<string> unsortedTitles)
    {
      if(unsortedTitles == null) return null;  
      unsortedTitles.Sort(new TitleComparer());
       
      return unsortedTitles;
    }
    
    private class TitleComparer : IComparer<string>
    {
    public int Compare(string firstTitle, string secondTitle)
      {
        if (firstTitle == null || secondTitle == null) return firstTitle.CompareTo(secondTitle);
        
        firstTitle = firstTitle.TrimEnd();
        secondTitle = secondTitle.TrimEnd();

        string regexPattern = @"^(the |a |an )";
        Regex regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
        string changedX = firstTitle;
        string changedY = secondTitle;

        if (regex.IsMatch(firstTitle))
        {
          var correctTitle = Regex.Replace(firstTitle, regexPattern, "", RegexOptions.IgnoreCase);
          changedX = $"{correctTitle}, {regex.Match(firstTitle).Value}";
        }

        if (regex.IsMatch(secondTitle))
        {
          var correctTitle = Regex.Replace(secondTitle, regexPattern, "", RegexOptions.IgnoreCase);
          changedY = $"{correctTitle}, {regex.Match(secondTitle).Value}";
        }

        return changedX.CompareTo(changedY);
      }
    }
  }
}

答案10:

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

namespace Kata
{
  public class TitleSorter
  {
    public List<string> Sort(List<string> unsortedTitles)
    {
       if(unsortedTitles == null) return null;  
       unsortedTitles.Sort(new Title());
       
            return unsortedTitles;
    }
  }
  
  public class Title : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            if(x == null || y== null) return x.CompareTo(y); 
            x = x.TrimEnd();
            y = y.TrimEnd();           
        
            string pattern = @"^(the |a |an )";
            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
            string changedX = x;
            string changedY = y;

            if (reg.IsMatch(x))
            {
                changedX = Regex.Replace(x, pattern, "", RegexOptions.IgnoreCase) + ", " + reg.Match(x).Value;
            }
            if (reg.IsMatch(y))
            {
                changedY = Regex.Replace(y, pattern, "", RegexOptions.IgnoreCase) + ", " + reg.Match(y).Value;
            }
            return changedX.CompareTo(changedY);
        }
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值