工作中用到一个字符串排序,类似于windows中文件夹的排序,本来也没有什么,排序用冒泡算法就行了。
不过字符串对比,没有找到系统自带的方法,只好自己写一个。
排序采用Asciid码表,例如1与a,则a是大的;
同样字符的话,取长度最大的,例如aa与aaa,取aaa为大;如果是aab与aaa,自然是aab为最大;
/// <summary> /// 比较两个字符串的大值(按ascii) /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <returns></returns> private static string maxString(string s1, string s2) { //一些非空判断 if (string.IsNullOrWhiteSpace(s1)) return s2; if (string.IsNullOrWhiteSpace(s2)) return s1; if (s1.Trim() == "") return s2; if (s2.Trim() == "") return s1; //对比 int minlen = s1.Length < s2.Length ? s1.Length : s2.Length; char[] c1 = s1.ToCharArray(); char[] c2 = s2.ToCharArray(); char[] max = null; for (int i = 0; i < minlen; i++) { if (c1[i] != c2[i]) { max = c1[i] > c2[i] ? c1 : c2; break; } } if (max == null) max = c1.Length > c2.Length ? c1 : c2; return new string(max); } /// <summary> /// 比较两个字符串的小值(按ascii) /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <returns></returns> private static string minString(string s1, string s2) { //一些非空判断 if (string.IsNullOrWhiteSpace(s1)) return s2; if (string.IsNullOrWhiteSpace(s2)) return s1; if (s1.Trim() == "") return s2; if (s2.Trim() == "") return s1; //对比 int minlen = s1.Length < s2.Length ? s1.Length : s2.Length; char[] c1 = s1.ToCharArray(); char[] c2 = s2.ToCharArray(); char[] min = null; for (int i = 0; i < minlen; i++) { if (c1[i] != c2[i]) { min = c1[i] < c2[i] ? c1 : c2; break; } } if (min == null) min = c1.Length < c2.Length ? c1 : c2; return new string(min); }