Say you want to compare two strings in C++ to see if they are the same. Aside from less typing, is there any difference between the following? Is one faster than the other, and is there a better way to compare the strings than what is contained here?
Version A:
if( string1 == string2 ) { return true; }
Version B:
// Check for equal length, then...
for( int i = 0; i < string1.length(); ++i ) {
if( string1[i] != string2[i] ) { return false; }
}
return true;
Is there any difference between the following?
Yes. Your code doesn't check the length of the strings, so if the first string is longer than the second string you can end up reading past the end of the second string. If the first string is a proper prefix of the second string your code returns the wrong result.
Is one faster than the other?
Using the standard library functions will likely be the same or faster than your own function, because standard library functions can be optimized better. For example, the ==
operator might use std::memcmp
to compare multiple characters at a time.
Is there a better way to compare the strings than what is contained here?
No, not really. string1 == string2
is probably as good as it gets in terms of both simplicity and speed.