Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the way to compare string in an efficient way in C++

Tags:

c++

string

Is it efficient to compare a string with another string or string literal like this?

string a;
string b;
if (a == "test")

or

if (a == b)

My coworker asked me to use memcmp

Any comments about this?

Thanks.

like image 453
skydoor Avatar asked Nov 10 '10 15:11

skydoor


People also ask

How do I properly compare strings in C?

C strcmp() In this tutorial, you will learn to compare two strings using the strcmp() function. The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

Can you use == to compare strings 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.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


4 Answers

Yes use a == b, do not listen to your co-worker.

You should always prefer code readability and using STL over using C functions unless you have a specific bottleneck in your program that you need to optimize and you have proven that it is truly a bottleneck.

like image 91
Brian R. Bondy Avatar answered Nov 15 '22 18:11

Brian R. Bondy


Obviously you should use a == b and rely on its implementation.

For the record, std::char_traits<char>::compare() in a popular implementation relies on memcmp(), so calling it directly would only be more painful and error-prone.

like image 40
icecrime Avatar answered Nov 15 '22 17:11

icecrime


If you really need to know, you should write a test-application and see what the timing is.

That being said, you should rely on the provided implementation being quite efficient. It usually is.

like image 37
Björn Pollex Avatar answered Nov 15 '22 19:11

Björn Pollex


I think your coworker is a bit hooked up on possible optimization.

  • memcmp isn't intended to compare strings (that would be strcmp)
  • to only compare upto the size of the shortest string, you would need strlen on both strings
  • memcmp returns <0, =0, >0, which is a nuisance to always remember
  • strcmp and strlen can cause weird behaviour with bad c-style strings (not ending with \0 or null)
like image 31
stefaanv Avatar answered Nov 15 '22 17:11

stefaanv