真正不相等的字符串,string.Compare是否可以返回0?
作者:互联网
我正在考虑string.Compare()在C#中如何工作的数学原理.
在此方法调用中,两个不相等的字符串是否有可能返回0?
我指的是真正不相等的字符串,例如“ Herp”和“ Derp”,而不是“ Herp”和“Hěrp”
不幸的是,除了基本的空值情况外,source code for string.Compare
都是内部组件-.NET之外.
我相信this是用于此的实际C代码,但很难确定.
我正在考虑的情况:
>奇怪的序数行为(只是最终导致相等的字符串排列)
>溢出整数,导致比较的正数和负数,结果为0
>还有其他比我更精通mscorlib实现的人
提出这个问题没有特定的原因-只是出于好奇.而且我以前没有看到它要求C#!
解决方法:
我认为,从技术上讲,您的问题的答案是肯定的,具体取决于您调用的重载和传递的选项参数.
根据MSDN docs,可以对具有对字符序数值有奇怪规则的文化进行比较,甚至可以跳过某些字符:
Notes to Callers
Character sets include ignorable characters. The Compare(String,
String) method does not consider such characters when it performs a
culture-sensitive comparison. For example, if the following code is
run on the .NET Framework 4 or later, a culture-sensitive comparison
of “animal” with “ani-mal” (using a soft hyphen, or U+00AD) indicates
that the two strings are equivalent.
如果要忽略区域性,仅比较2个字符串的原始值,则可以调用重载String.Compare(s1,s2,StringComparison.OrdinalIgnoreCase).这实际上将导致逐字节比较. Docs:
Notes to Callers … To
recognize ignorable characters in your comparison, supply a value of
StringComparison.Ordinal or OrdinalIgnoreCase for the comparisonType
parameter.
请注意,“较大”或“较小”字符串的定义不一定很明显.例如,字符串“ abc”大于或小于“ abcc”吗? .NET非常清楚,它用于字符串比较的目的较小.但是,在依靠这种极端情况之前,请仔细阅读文档:
The comparison terminates when an inequality is discovered or both
strings have been compared. However, if the two strings compare equal
to the end of one string, and the other string has characters
remaining, the string with remaining characters is considered greater.
The return value is the result of the last comparison performed.
标签:string-comparison,string,c 来源: https://codeday.me/bug/20191028/1951702.html