#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';
}