1 int compare ( const string& str ) const;
2 int compare ( const char* s ) const;
3 int compare ( size_t pos1, size_t n1, const string& str ) const;
4 int compare ( size_t pos1, size_t n1, const char* s) const;
5 int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 ) const;
6 int compare ( size_t pos1, size_t n1, const char* s, size_t n2) const;
Compares the content of this object (or a substring of it, known as compared (sub)string
) to the content of a comparing string
, which is formed according to the arguments passed.
The member function returns 0
if all the characters in the
compared contents compare equal, a negative value if the first
character that does not match compares to less in the object than in
the comparing string
, and a positive value in the opposite case.
Notice that for string
objects, the result of a character comparison depends only on its character code (i.e., its ASCII
code), so the result has some limited alphabetical or numerical ordering meaning.
For other basic_string
class instantitations, the comparison depends on the specific traits
::compare function, where traits
is one of the class template parameters.
if the compared characters sequences are equal, otherwise a number different from 0
is returned, with its sign indicating whether the object is considered greater than the comparing string
passed as parameter (positive sign), or smaller (negative sign).
1 // comparing apples with apples
2 #include <iostream>
3 #include <string>
4 using namespace std;
6 int main ()
8 string str1 ("green apple");
9 string str2 ("red apple");
11 if (str1.compare(str2) != 0)
12 cout << str1 << " is not " << str2 << "\n";
14 if (str1.compare(6,5,"apple") == 0)
15 cout << "still, " << str1 << " is an apple\n";
17 if (str2.compare(str2.size()-5,5,"apple") == 0)
18 cout << "and " << str2 << " is also an apple\n";
20 if (str1.compare(6,5,str2,4,5) == 0)
21 cout << "therefore, both are apples\n";
23 return 0;