I have a question:
Let's say there are two std::string
s and I want to compare them, there is the option of using the compare()
function of the string
class but I also noticed that it is possible using simple < > !=
operators (both of the cases are possible even if I don't include the <string>
library). Can someone explain why the compare()
function exists if a comparison can be made using simple operators?
btw I use Code::Blocks 13.12 here is an example of my code:
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; using std::getline; int main() { string temp1, temp2; cout << "Enter first word: "; getline (cin,temp1); cout << "Enter second word: "; getline (cin,temp2); cout << "First word: " << temp1 << endl << "Second word: " << temp2 << endl; if (temp1 > temp2) { cout << "One" << endl; } if (temp1.compare(temp2) < 0) { cout << "Two" << endl; } return 0; }
Because C strings are array of characters. Arrays are simply pointers to the first element in the array, and when you compare two pointers using == it compares the memory address they point to, not the values that they point to.
The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
.compare()
returns an integer, which is a measure of the difference between the two strings.
0
indicates that the two strings compare as equal. operator==
simply returns a boolean, indicating whether the strings are equal or not.
If you don't need the extra detail, you may as well just use ==
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With