what is your best string comparison algorithm?
i find O(n)
#include <string>
bool str_cpmr(char* str1, char* str2)
{
int l1 = strlen(str1), l2 = strlen(str2) ;
if(l1 != l2)
return false;
for(int i = 0 ; i < l1 ; i++)
if(str1[i] != str2[i])
return false ;
return true ;
}
and i wonder if there is any other / better solution.
also, how to test that accurately?
i propose to compare
- 100 matches
- 100 strings differing by one char swap
is there more to test string compare ?
how is it in stl c++ (slt string::compare) ?
thanks!!!!!
You function is O(n), but still takes roughly double the time necessary —
strlenwalks through the string to find the length, then (assuming they’re the same length) you walk through the strings again comparing the characters.Instead of that, I’d walk through the strings until you reach a mismatch or the end of both strings. If you reach a mismatch, you return false. You return true if and only if you reach the end of both strings (simultaneously) without any mismatches first.