35 通过mismatch或者lexicographical_compare实现忽略大小写字符串的比较

本文介绍了三种字符串比较的方法:使用mismatch函数、使用lexicographical_compare函数以及使用C库函数stricmp(strcasecmp)。这些方法适用于不区分大小写的字符串比较场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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下的
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值