In C++, std::string::compare() compares this string with another string (or a piece of one) in dictionary order.
Return value is like C strcmp: negative, zero, or positive. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Compare full strings or slices.
C++
int c = a.compare(b);
int d = a.compare(0, 3, b);
Call
What it does
a.compare(b)
Compare all of a with all of b.
a.compare(pos, len, b)
Compare a slice of a with b.
For simple equality, prefer a == b. Use compare when you need ordering or substring compares.
Library declarations
C++
int compare(const string& str) const noexcept;
int compare(size_type pos, size_type len, const string& str) const;
Parameters
Parameter
Description
other / slice args
The string or substring to compare against.
Return Value
Return Value
Description
int
0 if equal; <0 if *this is less; >0 if greater.
C++ Examples
Example 1 — Basic compare()
Compare two equal words.
C++
#include <iostream>
#include <string>
int main() {
std::string a = "cat";
std::string b = "cat";
std::cout << a.compare(b) << '\\n';
return 0;
}