
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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? Yes, 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
In the example code below, we will compare two strings using both the == operator and the compare() function to see the differences in their behavior.
#include <iostream> #include <string> using namespace std; int main() { string str1 = "apple"; string str2 = "apple"; string str3 = "banana"; // Using '==' operator if (str1 == str2) { cout << "str1 is equal to str2 using '=='" << endl; } else { cout << "str1 is not equal to str2 using '=='" << endl; } if (str1 == str3) { cout << "str1 is equal to str3 using '=='" << endl; } else { cout << "str1 is not equal to str3 using '=='" << endl; } // Using compare() function int result = str1.compare(str2); if (result == 0) { cout << "str1 is equal to str2 using compare()" << endl; } else if (result < 0) { cout << "str1 is less than str2 using compare()" << endl; } else { cout << "str1 is greater than str2 using compare()" << endl; } result = str1.compare(str3); if (result == 0) { cout << "str1 is equal to str3 using compare()" << endl; } else if (result < 0) { cout << "str1 is less than str3 using compare()" << endl; } else { cout << "str1 is greater than str3 using compare()" << endl; } return 0; }
The output of the above code will be:
str1 is equal to str2 using '==' str1 is not equal to str3 using '==' str1 is equal to str2 using compare() str1 is less than str3 using compare()