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

 

posted @ 2012-12-08 21:28  大气象  阅读(13824)  评论(1编辑  收藏  举报
http://www.tianqiweiqi.com