带数字的字符串排序Qt

文章讲述了在日常开发中遇到字符串按数字顺序排列的问题,介绍了如何使用C++的std::sort和自定义比较函数对包含数字的字符串列表进行正确排序的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

日常开发中排序操作是很常见的,大多时候使用qSort默认方式,就可以满足需求;

但是遇到字符串中包含1、2、3、10、11、12、21、22、31这种时,顺序就会乱掉;

目前我遇到的情况是:

DLC-30A/50A
DLC-30A/50A_2.2
DLG-30A_1
DLG-30A_2
DLT-30A
Remote-auto-1
Remote-auto-2
Remote-auto-3
Remote-auto-4
Remote-auto-5
Remote-auto-6
Remote-auto-7
Remote-auto-8
Remote-auto-9
Remote-auto-10
Remote-auto-11
Remote-auto-12
Remote-auto-13
Remote-auto-14
Remote-auto-15
Remote-auto-16
Remote-auto-17
Remote-auto-18
Remote-auto-19
Remote-auto-20
Remote-auto-21
Remote-18004
def1
multi_cast

按照正常的排序算法,得到的可能是如下的字符串:

DLC-30A/50A
DLC-30A/50A_2.2
DLG-30A_1
DLG-30A_2
DLT-30A
Remote-18004
def1
multi_cast
Remote-auto-1
Remote-auto-10
Remote-auto-11
Remote-auto-12
Remote-auto-13
Remote-auto-14
Remote-auto-15
Remote-auto-16
Remote-auto-17
Remote-auto-18
Remote-auto-19
Remote-auto-2
Remote-auto-20
Remote-auto-21
Remote-auto-3
Remote-auto-4
Remote-auto-5
Remote-auto-6
Remote-auto-7
Remote-auto-8
Remote-auto-9

为了将其按照最后面数字进行正确排序,可以使用如下算法:

void SortDSName(QStringList& names)
{
    std::sort(names.begin(), names.end(),[](QString &mIt, QString &nIt){
        QStringList mStr=mIt.mid(1).split(".");
        QStringList nStr=nIt.mid(1).split(".");
        int num = mStr.length() < nStr.length() ? mStr.length() : nStr.length();
        for(int i = 0; i < num; i++)
        {
            //if(mStr[i].toInt() == nStr[i].toInt())
            if(mStr[i] == nStr[i]) {
                continue;
            } else {
                return mStr[i].toInt() < nStr[i].toInt();
            }
        }
        return mStr.length() < nStr.length();
    });
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值