STL Algorithm
std::lexicographical_compare is an algorithm which can be used to compare string lexicographically.
We can give our comparing function to make it work without pay attention to capital and small letter.
We can give our comparing function to make it work without pay attention to capital and small letter.
C++
template< class InputIt1, class InputIt2, class Compare >
constexpr bool lexicographical_compare( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
Compare comp );
Example:
C++
#include
#include
#include
#include
using namespace std;
int main()
{
string s1 = "Abcf";
string s2 = "AbCf";
// return true if the first range is lexicographically less than the second.
cout << "lexicographical_compare: " << lexicographical_compare( s1.begin(), s1.end(),
s2.begin(), s2.end() )
<< endl;
// ignore difference about capital and small letter, check whether they are same characters.
cout << "second result: " << lexicographical_compare( s1.begin(), s1.end(),
s2.begin(), s2.end(),
[](const char c1, const char c2){ return tolower(c1) == tolower(c2); } )
<< endl;
return 0;
}
Output:
Bash
lexicographical_compare: 0
second result: 1
Standard C Library
There is a similar function in the standard C library:
int strcasecmp(const char *s1, const char *s2);
It compares strings ignoring case.Example:
C++
#include
using namespace std;
int main()
{
string s1 = "Abcf";
string s2 = "ABCf";
// return 0 if both charater is equal (ignore case)
cout << strcasecmp( s1.c_str(), s2.c_str() ) << endl;
return 0;
}