目的
实现如下功能:
std::string str1 = "iloveyou";
std::string str2 = "ILoveYou";
if (icasecompare(str1, str2)) {
cout << "str1 is equal to str2\n";
}
bool icasecompare(const string& s1, const string& s2)
{
//?
}
使用系统库
这是比较简单的方法,但由于不是c++标准的一部分,不同平台的编译器支持需要测试:
bool icasecompare(const string& s1, const string& s2)
{
#ifdef __LINUX__
return (strcasecmp(str1.c_str(), str2.c_str()) == 0); // #include <cstring>
#else
return (stricmp(str1.c_str(), str2.c_str()) == 0);
#endif
}
使用std::transform
把待比较的字符串统统转换为小写字符,再作比较:
#include <algorithm>
bool icasecompare( const std::string& str1, const std::string& str2 ) {
// 拷贝临时对象,算法在临时对象上作更改
std::string str1Cpy( str1 );
std::string str2Cpy( str2 );
std::transform( str1Cpy.begin(), str1Cpy.end(), str1Cpy.begin(), ::tolower );
std::transform( str2Cpy.begin(), str2Cpy.end(), str2Cpy.begin(), ::tolower );
return ( str1Cpy == str2Cpy );
}
使用std::equal
stl中的std::equal可以达到这个目的:
bool icompare_pred(unsigned char a, unsigned char b)
{
return std::tolower(a) == std::tolower(b);
}
bool icasecompare(std::string const& a, std::string const& b)
{
if (a.length() == b.length()) {
return std::equal(b.begin(), b.end(),
a.begin(), icompare_pred);
}
else {
return false;
}
}
当然,有了c++11,使用Lambda会方便些:
bool icasecompare(const string& a, const string& b)
{
if (a.length() == b.length()) {
return std::equal(a.begin(), a.end(), b.begin(),
[](char a, char b) {
return tolower(a) == tolower(b);
});
else {
return false;
}
}
使用boost库
使用boost,就不用自己动手创建一个新函数了,直接使用:
#include <boost/algorithm/string.hpp>
// Or, for fewer header dependencies:
//#include <boost/algorithm/string/predicate.hpp>
return boost::iequals(str1, str2);
小结
考虑到跨平台和系统兼容性,不建议使用第一种方式。
从编码角度,如果有boost,直接使用boost即可。
否则,使用c11支持的Lambda表达式。