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
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM