Some time ago I found this function (unfortunately, I don't remember from where it came from, most likely from some Python framework) that compares two strings and returns a bool value. It's quite simple to understand what's going on here. Finding xor between char returns 1 (True) if they do not match.
def cmp_strings(str1, str2):
return len(str1) == len(str2) and sum(ord(x)^ord(y) for x, y in zip(str1, str2)) == 0
But why is this function used? Isn't it the same as str1==str2
?
Approach: The idea is to iterate over both the string character by character and if the character mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string.
The compare() function in C++ The compare() function compares two strings and returns the following values according to the matching cases: Returns 0, if both the strings are the same. Returns <0, if the value of the character of the first string is smaller as compared to the second string input.
We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
Important points about String comparison 1) You can compare two String variable using == operator but you should never do this because it will return true if you compare String literals but return false if you compare String object to a literal or two String object, even if they have same characters.
It takes a similar amount of time to compare any strings that have the same length. It's used for security when the strings are sensitive. Usually it's used to compare password hashes.
If ==
is used, Python stops comparing characters when the first one not matching is found. This is bad for hashes because it could reveal how close a hash was to matching. This would help an attacker to brute force a password.
This is how hmac.compare_digest
works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With