c语言数字和字母排序,C# 数字和字母的混合排序

C#中 List默认的Sort 并不符合本人的要求;本人的要求是这样;

0000到9999

有哪位高手能给本人解答一下,本人本人写了类实现IComparer的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 

{

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 

{

ch1 = x[marker1];

}

else

{

break;

}

} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

do

{

space2[loc2++] = ch2;

marker2++;

if (marker2 

{

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

可以理解为“全数字”

你要比较的字符串定长吗?假如定长就不需要再判断长度了,假如不定长,你给的逻辑就不够了。下面以定长4字符为例:

public int Compare(string x, string y)

{

if(x[1] >= "A" && y[1] 

return 1;

if(x[1] = "A")

return -1;

//至此,第2位要么同时为字母,要么同时为数字,两者顺序逐字符比较即可

for(int i=0;i<4;i++){

if(x[i] 

if(x[i] > y[i]) return 1;

}

return 0;

}

1

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

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# 数字和字母的混合排序!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值