
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Difference between Relational operator(==) and std::string::compare() in C++
There is only one difference between the relational operator == and std::string::compare(). That is the return value. Internally, string::operator==() is using string::compare()
Relational operator(==) returns a boolean just signifying whether the 2 strings are equal or not while compare returns an integer that signifies how the strings relate to each other.
To elaborate on the use cases, compare() can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. For example,
Example
#include <iostream> using namespace std; int main() { string s1 = "Tutorials Point"; string s2 = "Hello World"; cout << s1 == s2; cout << s1.compare(s2); cout << s2.compare(s1); return 0; }
Output
This will give the output −
0 1 -1
- Related Articles
- Difference between std::vector and std::array in C++
- Difference between Relational Algebra and Relational Calculus
- Difference between "new operator" and "operator new" in C++?
- String compare by == operator in Java
- Differences between C++ string == and compare()?
- What is the difference between "std::endl" and "\n" in C++?
- Difference between Hierarchical Database and Relational Database
- Difference Between Copy Constructor and Assignment Operator in C++
- Remove spaces from std::string in C++
- What are the differences between -std = c++11 and -std = gnu++11?
- Difference between == and === operator in JavaScript
- Difference between !== and ==! operator in PHP
- Difference Between E-R Model and Relational Model in DBMS
- Difference between String and StringBuilder in C#
- Parsing a comma-delimited std::string in C++

Advertisements