Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between CompareStr and '=' for Strings in Delphi

Tags:

delphi

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.

like image 475
CyprUS Avatar asked Jun 23 '11 10:06

CyprUS


1 Answers

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.

like image 149
Rob Kennedy Avatar answered Sep 28 '22 16:09

Rob Kennedy