Search code examples
delphiansistring

Delphi - AnsiString Not Equal but dont know why


I have a comparison operator for a Tree iteration. It uses AnsiString variables. My issue is that when the values appear to be equal, I am not getting an equal indicator (aka not getting 0 from System.AnsiStrings.CompareStr). I have looked at my variables via the debbugger and stepped through my code. Both variables are AnsiStrings, both are the same value, and there are no spaces. CompareStr returns -65 if that helps any.

What can I be overlooking? Here is my code.

  function CompareNodes(idVal: pointer; ANode: TALStringKeyAVLBinaryTreeNode): Integer;
  var
    Key1, Key2: AnsiString;
  begin
    Key1 := PAnsiString(idVal)^;
    Key2 := ANode.ID;

    Result := System.AnsiStrings.CompareStr(Key1, Key2);
  end;

Solution

  • It is interesting to note that 65 is the difference between A and #0.

    Since the line Key1 := PAnsiString(idVal)^; performs a unchecked type-cast of of the idVal pointer, there is the possibility that idVal is actually referring to a Wide/Unicode string. This would mean Key1 is trying to treat a non AnsiString as if it were one.

    Based on OP's comment:

    Found my answer....Somehow a string was being used for input, not an AnsiString. The -65 might be an indicator when this situation occurs...

    That is exactly the problem.