c++忽略大小写的字符串比较方法

目的

实现如下功能:

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表达式。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值