使用mismatch:
int ciCharCompare(char c1,char c2)
{
int lc1 = tolower(static_cast<unsigned char>c1);
int lc2 = tolower(static_cast<unsigned char>c2);
if(lc1 < lc2)
return -1;
if(lc1 > lc2)
return 1;
return 0;
}
int ciStringCompare(const string& s1,const string& s2)
{
if(s1.size() < s2.size())
return ciCharCompareImp(s1,s2);
else
return -ciCharCompareImp(s2,s1);
}
int ciCharCompareImp(const string& s1,const string& s2)
{
typedef pair<string::const_iterator,string::const_iterator> PSCI;
PSCI p = mismatch(
s1.begin(),s1.end(),
s2.begin(),
not2(ptr_fun(ciCharCompare))
);
if(p.first == s1.end())
{
if(p.second == s2.end())
return 0;
else
return -1;
}
return ciCharCompare(*p.first,*p.second);
}
使用lexicographical_compare:
bool ciCharLess(char c1,char c2)
{
return tolower(static_cast<unsigned char>c1) < tolower(static_cast<unsigned char>c2);
}
bool ciStringCompare(const string& s1,const string& s2)
{
return lexicographical_compare(s1.begin(),s1.end(),
s2.begin(),s2.end(),
ciCharLess);
}
最简单的方法,使用C的库函数stricmp(并不使用STL库,效率最快):
int ciStringCompare(const string& s1,const string& s2)
{
return strcasecmp(s1.c_str(),s2.c_str()); //stricmp是windows下的,strcasecmp是linux下的
}