c# 数字字母混合排序比较器

项目上涉及到一些编码的排序,网上找了一下没有合适的比较器,于是自己动手编写了一个。供大家学习参考。

 class StringComparer : IComparer<string>
        {
            public bool MatchCase { get; }
            public StringComparer(bool matchCase) { MatchCase = matchCase; }
            private int CharCompare(char a, char b, bool matchCase)
            {
                char _a = char.MinValue, _b = char.MinValue;
                if (matchCase) { _a = a; _b = b; }
                else { _a = char.ToUpper(a); _b = char.ToUpper(b); }
                if (_a > _b) return 1;
                if (_a < _b) return -1;
                return 0;
            }
            public int Compare(string x, string y)
            {
                int len;
                if (x.Length > y.Length) len = x.Length;
                else len = y.Length;
                string numericx = "";
                string numericy = "";
                for (int i = 0; i < len; i++)
                {
                    char cx = char.MinValue;
                    char cy = char.MinValue;
                    if (i < x.Length) cx = x[i];
                    if (i < y.Length) cy = y[i];
                    if (cx >= 48 && cx <= 57) numericx += cx;
                    if (cy >= 48 && cy <= 57) numericy += cy;
                    if (i == len - 1)
                    {
                        if (numericx.Length > 0 && numericy.Length > 0)
                        {
                            if (decimal.Parse(numericx) < decimal.Parse(numericy)) return -1;
                            if (decimal.Parse(numericx) > decimal.Parse(numericy)) return 1;
                        }
                        return CharCompare(cy, cy, MatchCase);
                    }
                    if ((cx >= 48 && cx <= 57) && (cy >= 48 && cy <= 57)) continue;
                    if (numericx.Length > 0 && numericy.Length > 0)
                    {
                        if (decimal.Parse(numericx) < decimal.Parse(numericy)) return -1;
                        if (decimal.Parse(numericx) > decimal.Parse(numericy)) return 1;
                    }
                    if (CharCompare(cx, cy, MatchCase) == 0) continue;
                    return CharCompare(cx, cy, MatchCase);
                }
                return 0;
            }
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值