| string (1) | int compare (const basic_string& str) const; |
|---|---|
| substrings (2) | int compare (size_type pos, size_type len, const basic_string& str) const;int compare (size_type pos, size_type len, const basic_string& str, size_type subpos, size_type sublen) const; |
| c-string (3) | int compare (const charT* s) const;int compare (size_type pos, size_type len, const charT* s) const; |
| buffer (4) | int compare (size_type pos, size_type len, const charT* s, size_type n) const; |
| string (1) | int compare (const basic_string& str) const noexcept; |
|---|---|
| substrings (2) | int compare (size_type pos, size_type len, const basic_string& str) const;int compare (size_type pos, size_type len, const basic_string& str, size_type subpos, size_type sublen) const; |
| c-string (3) | int compare (const charT* s) const;int compare (size_type pos, size_type len, const charT* s) const; |
| buffer (4) | int compare (size_type pos, size_type len, const charT* s, size_type n) const; |
| string (1) | int compare (const basic_string& str) const noexcept; |
|---|---|
| substrings (2) | int compare (size_type pos, size_type len, const basic_string& str) const;int compare (size_type pos, size_type len, const basic_string& str, size_type subpos, size_type sublen = npos) const; |
| c-string (3) | int compare (const charT* s) const;int compare (size_type pos, size_type len, const charT* s) const; |
| buffer (4) | int compare (size_type pos, size_type len, const charT* s, size_type n) const; |
| value | relation between compared string and comparing string |
|---|---|
| 0 | They compare equal |
| <0 | Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter. |
| >0 | Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer. |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// comparing apples with apples
#include <iostream>
#include <string>
int main ()
{
std::string str1 ("green apple");
std::string str2 ("red apple");
if (str1.compare(str2) != 0)
std::cout << str1 << " is not " << str2 << '\n';
if (str1.compare(6,5,"apple") == 0)
std::cout << "still, " << str1 << " is an apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)
std::cout << "and " << str2 << " is also an apple\n";
if (str1.compare(6,5,str2,4,5) == 0)
std::cout << "therefore, both are apples\n";
return 0;
}
green apple is not red apple still, green apple is an apple and red apple is also an apple therefore, both are apples