首页 > 代码库 > c# 字符串排序 (面试题)
c# 字符串排序 (面试题)
将一些字符串,如: "bc", "ad", "ac", "hello", "xman", "little", "during","day"
排序的结果:“ad”,"ac",“bc”,“during”,“day”,“hello”,“little”,“xman”
采用框架自带的排序函数来调用自定义的Compare方法实现,代码段如下所示:
class Program { static void Main(string[] args) { string[] strArr = new string[] { "bc", "ad", "ac", "hello", "xman", "little", "during", "day"}; List<string> strs = new List<string>(); list.AddRange(strArr); /* * Sort string by asc * result : “ad”,"ac",“bc”,“during”,“day”,“hello”,“little”,“xman” */ list.Sort(new CompStr()); foreach (string str in strs) { Console.WriteLine(str); } Console.WriteLine("------------"); //Sort string by desc list.Sort(new CompStrDesc()); foreach (string str in strs) { Console.WriteLine(str); } Console.ReadLine(); } } public class CompStr : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { if (x.Length > 0 && y.Length > 0) { if (x[0].CompareTo(y[0]) == 0) { return -x.CompareTo(y); } } return x.CompareTo(y); } #endregion } public class CompStrDesc : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { if (x.Length > 0 && y.Length > 0) { if (x[0].CompareTo(y[0]) == 0) { return x.CompareTo(y); } } return -x.CompareTo(y); } #endregion }
c# 字符串排序 (面试题)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。