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 CompareStr
not 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:
if str1[i] = str2[i] then begin
// They're equal
end else if str1[i] < str2[i] then begin
// str1 comes first
end else begin
// str2 comes first
end;
That compares str1
and str2
twice. With CompareStr
, you can cut out one of the string comparisons and replace it with a cheaper integer comparison:
x := CompareStr(str1[i], str2[i]);
if x = 0 then begin
// They're equal
end else if x < 0 then begin
// str1 comes first
end else begin
// str2 comes first
end;
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 CompareText
and AnsiCompareStr
. 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. Use CompareStr
when you need the extra functionality it provides.
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