C# 数字和字母的混合排序

.Net技术 码拜 8年前 (2016-09-23) 2835次浏览
C#中 List默认的Sort 并不符合本人的要求;本人的要求是这样;
0000到9999<A000到Z999<0A00到ZZ99;
有哪位高手能给本人解答一下,本人本人写了类实现IComparer<string>的Compare方法
public int Compare(string x, string y)
{
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
int i1, i2;
if (int.TryParse(x, out i1) && int.TryParse(y, out i2))
{
return i1.CompareTo(i2);
}
else
{
int len1 = x.Length;
int len2 = y.Length;
int marker1 = 0;
int marker2 = 0;
while (marker1 < len1 && marker2 < len2)
{
char ch1 = x[marker1];
char ch2 = y[marker2];
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = x[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = y[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
string str1 = new string(space1);
string str2 = new string(space2);
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
}
return x.Length – y.Length;
}
程序在处理 第一位是数字 第二位是字母时 排序有问题
解决方案

39

引用

0000到9999<A000到Z999<0A00到ZZ99

可以理解为“全数字”<“首位字母”<“第二位字母”
你要比较的字符串定长吗?假如定长就不需要再判断长度了,假如不定长,你给的逻辑就不够了。下面以定长4字符为例:

        public int Compare(string x, string y)
        {
            if(x[1] >= "A" && y[1] < "A")
				return 1;
			if(x[1] < "A" && y[1] >= "A")
				return -1;

			//至此,第2位要么同时为字母,要么同时为数字,两者顺序逐字符比较即可
			for(int i=0;i<4;i++){
				if(x[i] < y[i]) return -1;
				if(x[i] > y[i]) return 1;
			}

			return 0;
        }

1

然后能否存在长度不一致的情况?

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# 数字和字母的混合排序
喜欢 (0)
[1034331897@qq.com]
分享 (0)