stl忽略字符大小写的字符串比较

#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

//参考effective stl 35
namespace Compare1
{
	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 ciStringCompareImpl(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)));	ptr_fun已弃用
			not2(function<bool(char, char)>(ciCharCompare)));

		if (p.first == s1.end())					//如果为true,要么s1和s2相等,或者s1比s2短
		{				
			if (p.second == s2.end()) return 0;
			else return -1;
		}

		return ciCharCompare(*p.first, *p.second);
	}

	int ciStringCompare(const string &s1, const string &s2)
	{
		if (s1.size() <= s2.size()) return ciStringCompareImpl(s1, s2);
		else return -ciStringCompareImpl(s2, s1);
	}
}

namespace Compare2
{
	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)
	{
		//lexicographical_compare s1 >= s2 返回false
		return lexicographical_compare(s1.begin(), s1.end(),
			s2.begin(), s2.end(),
			ciCharLess);
	}
}

namespace Compare3
{
	//不使用stl vs2017
	bool ciStringCompare(const string &s1, const string &s2)
	{
		return _stricmp(s1.c_str(), s2.c_str());
	}
}

int main()
{
	cout << Compare1::ciStringCompare("hello", "HELLO") << endl;			//0
	cout << Compare1::ciStringCompare("hello world", "HELLO") << endl;		//1
	cout << Compare1::ciStringCompare("hello", "HELLO WORLD") << endl;		//-1

	cout << Compare2::ciStringCompare("hello", "HELLO") << endl;			//0
	cout << Compare2::ciStringCompare("hello world", "HELLO") << endl;		//0
	cout << Compare2::ciStringCompare("hello", "HELLO WORLD") << endl;		//1

	cout << Compare2::ciStringCompare("hello", "HELLO") << endl;			//0
	cout << Compare2::ciStringCompare("hello world", "HELLO") << endl;		//0
	cout << Compare2::ciStringCompare("hello", "HELLO WORLD") << endl;		//1
	
	return 0;
}

mismatch cppreferen.com示例

//此程序确定同时在给定字符串起始与在其结尾按逆序同时找到的最长子串(可能重叠)。
#include <iostream>
#include <string>
#include <algorithm>
 
std::string mirror_ends(const std::string& in)
{
    return std::string(in.begin(),
                       std::mismatch(in.begin(), in.end(), in.rbegin()).first);
}
 
int main()
{
    std::cout << mirror_ends("abXYZba") << '\n'
              << mirror_ends("abca") << '\n'
              << mirror_ends("aba") << '\n';
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值