I just want to know the difference between CompareStr and = for comparing strings in Delphi. Both yield the same result.
if(str2[i] = str1[i]) then
ShowMessage('Palindrome')
if(CompareStr(str2[i], str1[i]) = 0) then
ShowMessage('Palindrome')
Both show message Palindrome.
Use
CompareStrnot when you just want to see whether two strings are equal, but when you want to know how one string compares relative to another. It will return a value less than 0 if the first argument appears first, asciibetically, and it will return a value greater than zero if the first argument belongs after the second.Without
CompareStr, you might have code like this:That compares
str1andstr2twice. WithCompareStr, you can cut out one of the string comparisons and replace it with a cheaper integer comparison:As Gerry’s answer explains, the function is particularly useful in sorting functions, especially since it has the same interface as other comparison functions like
CompareTextandAnsiCompareStr. The sorting function is a template method, and each of the functions serves as a comparison strategy.If all you want to do is test for equality, use the
=operator — it’s easier to read. UseCompareStrwhen you need the extra functionality it provides.