QString对比,如起始为数字时以数字大小为准

2023-04-12  本文已影响0人  BrokenRainK
/**
* @brief compare 两个字符串对比,起始为数字时以数字大小为准
* @param str1
* @param str2
* @return 
*     =0: str1 = str2
*     <0: str1 < str2
*     >0: str1 > str2
*/
int Util::compare(const QString &str1, const QString &str2)
{
   if (str1.isEmpty() && str2.isEmpty())
       return 0;
   else if (str1.isEmpty() && !str2.isEmpty())
       return -1;
   else if (!str1.isEmpty() && str2.isEmpty())
       return 1;

   bool bDigit1 = str1.at(0).isDigit();
   bool bDigit2 = str2.at(0).isDigit();
   if (bDigit1)
   {
       int firstNumber1 = 0;
       QRegularExpression re("\\d+");
       QRegularExpressionMatch match = re.match(str1);
       if (match.hasMatch())
       {
           firstNumber1 = match.captured(0).toInt();
       }
       else
       {

       }

       if (bDigit2)
       {
           QRegularExpressionMatch match = re.match(str2);
           if (match.hasMatch())
           {
               int firstNumber2 = match.captured(0).toInt();
               if (firstNumber1 == firstNumber2)
                   return 0;
               else if (firstNumber1 < firstNumber2)
                   return -1;
               else
                   return 1;
           }
           else
           {

           }
       }
       else
           return 1;
   }
   else
   {
       if (bDigit2)
           return 1;
   }

   return QString::compare(str1, str2);
}
上一篇下一篇

猜你喜欢

热点阅读