|
实现简单的忽略大小写的字符串的比较
#include <iostream> #include <string> #include <algorithm> #include <utility> #include <functional> using std::pair; using std::cin; using std::cout; using std::endl; using std::string; using std::not2; using std::ptr_fun;
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); int ciStringCompare(const string& s1, const string& s2) { if (s1.size() <= s2.size()) { return ciStringCompareImpl(s1, s2); } else { return -ciStringCompareImpl(s2, s1); } }
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))); if (p.first == s1.end()) { if (p.second == s2.end()) { return 0; } else { return -1; } } return ciCharCompare(*p.first, *p.second); }
void PrintCompareResult(const string& s1, const string& s2) { if (ciStringCompare(s1, s2) > 0) { cout << s1 << " > " << s2 << endl; } else if (ciStringCompare(s1, s2) < 0) { cout << s1 << " < " << s2 << endl; } else { cout << s1 << " = " << s2 << endl; } }
int main() { string test1("FreeDomi"); string test2("FReedOmi"); PrintCompareResult(test1, test2); test1[6] = 'Z'; PrintCompareResult(test1, test2); test2[6] = 'z'; PrintCompareResult(test1, test2); return 0; }
运行效果如下图
|