Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between C++ string == and compare()?

Tags:

c++

string

I just read some recommendations on using

std::string s = get_string(); std::string t = another_string();  if( !s.compare(t) )  { 

instead of

if( s == t ) { 

I'm almost always using the last one because I'm used to it and it feels natural, more readable. I didn't even know that there was a separate comparison function. To be more precise, I thought == would call compare().

What are the differences? In which contexts should one way be favored to the other?

I'm considering only the cases where I need to know if a string is the same value as another string.

like image 498
Klaim Avatar asked Feb 06 '12 10:02

Klaim


People also ask

Can you compare strings with == in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can we use == for string comparison?

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 happens when you compare strings with ==?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

What is string compare in C?

strcmp() in C/C++ The function strcmp() is a built-in library function and it is declared in “string. h” header file. This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character.


1 Answers

This is what the standard has to say about operator==

21.4.8.2 operator==

template<class charT, class traits, class Allocator> bool operator==(const basic_string<charT,traits,Allocator>& lhs,                 const basic_string<charT,traits,Allocator>& rhs) noexcept; 

Returns: lhs.compare(rhs) == 0.

Seems like there isn't much of a difference!

like image 194
Bo Persson Avatar answered Oct 08 '22 06:10

Bo Persson