- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences between C++ string == and compare()?
In C++ we can compare two strings using compare() function and the == operator. Then the question is why there are two different methods? Is there any difference or not?
There are some basic differences between compare() and == operator. In C++ the == operator is overloaded for the string to check whether both strings are same or not. If they are the same this will return 1, otherwise 0. So it is like Boolean type function.
The compare() function returns two different things. If both are equal, it will return 0, If the mismatch is found for character s and t, and when s is less than t, then it returns -1, otherwise when s is larger than t then it returns +1. It checks the matching using the ASCII code.
Let us see an example to get the idea of the above discussion.
Example Code
#include <iostream> using namespace std; int main() { string str1 = "Hello"; string str2 = "Help"; string str3 = "Hello"; cout << "Comparing str1 and str2 using ==, Res: " << (str1 == str2) << endl;//0 for no match cout << "Comparing str1 and str3 using ==, Res: " << (str1 == str3) << endl;//1 for no match cout << "Comparing str1 and str2 using compare(), Res: " << str1.compare(str2) << endl;//checking smaller and greater cout << "Comparing str1 and str3 using compare(), Res: " << str1.compare(str3) << endl;//0 for no match }
Output
Comparing str1 and str2 using ==, Res: 0 Comparing str1 and str3 using ==, Res: 1 Comparing str1 and str2 using compare(), Res: -1 Comparing str1 and str3 using compare(), Res: 0
- Related Articles
- Differences between String and StringBuffer
- Difference between Relational operator(==) and std::string::compare() in C++
- What are the differences between compareTo() and compare() methods in Java?
- Differences between C++ and C#
- Differences between C and C#
- Major differences between C# and Java
- Compare two columns for matches and differences in Excel
- Compare between accounting and bookkeeping.
- Compare between tort and contract
- Compare between options and warrants
- What are the differences between C++ and Java?
- What are the differences between C and Java?
- What are the differences between C++ and Go?
- Java String comparison, differences between ==, equals, matches, compareTo().
- What are the differences between Thunderbolt and USB-C?
