Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings, c++

I have a question:

Let's say there are two std::strings 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; }     
like image 722
Medvednic Avatar asked Jul 25 '14 14:07

Medvednic


People also ask

Can I use == to compare strings in C?

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.

Can I compare strings in C?

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

Can you use == when comparing strings?

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.

What is strcmp function in C?

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.


1 Answers

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

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 ==.

like image 188
Tom Fenech Avatar answered Sep 30 '22 11:09

Tom Fenech