5

There's a bunch of ways you can compare strings in modern Delphi (say 2010-XE3):

  • '<=' operator which resolves to UStrCmp / LStrCmp
  • CompareStr
  • AnsiCompareStr

Can someone give (or point to) a description of what those methods do, in principle?

So far I've figured that AnsiCompareStr calls CompareString on Windows, which is a "textual" comparison (i.e. takes into account unicode combined characters etc). Simple CompareStr does not do that and seems to do a binary comparison instead.

But what is the difference between CompareStr and UStrCmp? Between UStrCmp and LStrCmp? Do they all produce identical results? Do those results change between versions of Delphi?

I'm asking because I need a comparison which will always produce the same results, so that indexes in app built with one version of Delphi remain consistent with code built with another.

4

1 回答 1

7

AnsiCompareStr被指定为考虑区域设置,并且无论 Delphi 版本如何,都应返回相同的结果,但可能会根据 Windows 版本和/或设置返回不同的结果。CompareStr是纯二进制比较:“比较操作基于 16 - 每个字符的位序值,不受当前语言环境的影响”(对于CompareStr(const S1, S2: string)重载)。UStrCmp还使用纯二进制比较:“字符串根据组成字符串的字符的序数值进行比较。” 所以后两者应该没有区别。它们返回结果的方式不同,因此需要两种实现(尽管可以使一种依赖于另一种)。

至于和之间的区别LStrCmp,取s,UStrCmp取s 。完全有可能两个字符(比如说 A 和 B)在错误命名的“ANSI”代码页中按 A < B 排序,但在 Unicode 中按 A > B 排序。您几乎总是应该使用适合数据的比较你有。LStrCmpAnsiStringUStrCmpUnicodeString

于 2013-06-03T12:13:49.330 回答