C++不区分大小写比较string类似CString.compareNoCase


使用transform();全转化为小写,然后对比string

#include < string>
#include <algorithm>

using  namespace std;

namespace BaseFunc
{
     //  string转小写
     string strToLower( const  string &str)
    {
         string strTmp = str;
        transform(strTmp.begin(),strTmp.end(),strTmp.begin(),tolower);
         return strTmp;
    }

     //  string.compareNoCase
     bool compareNoCase( const  string &strA, const  string &strB)
    {
         string str1 = strToLower(strA);
         string str2 = strToLower(strB);
         return (str1 == str2);
    }

     //  另一法
     bool compare( const  string& x,  const  string& y)
    {
         string::const_iterator p = x.begin();
         string::const_iterator q = y.begin();
         //  遍历对比每个字符
         while (p != x.end() && q != y.end() && toupper(*p) == toupper(*q))
        {
            ++p;
            ++q;
        }
         if (p == x.end())  //  如果x到结尾,y也到结尾则相等
        {
             return (q == y.end());
        }
         if (q == y.end())  //  如果x未到结尾,y到结尾返回false
        {
             return  false;
        }
         //  如果x,y都没有到结尾,说明有不相同的字符,返回false
         return  false;
         // return (toupper(*p) < toupper(*q));
    }
}

void main()
{
     string strA =  " abc ";
     string strB =  " AdC ";
     bool b = BaseFunc::compareNoCase( strA, strB );
    b = BaseFunc::compare( strA, strB );
}

string与CString互相转换:

string str;
CString s;
s = str.c_str();
str = s;
url: http://greatverve.cnblogs.com/archive/2012/12/08/string-compareNoCase.html

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM