不同字符串比较方法有什么区别
可能的重复:
C# 中字符串比较方法的差异
在 .NET 中,有许多字符串比较方法,我只是想确认考虑到性能,哪种方法最好。
string.Equals()
string.Compare()
string.CompareTo()
string.CompareOrdinal()
string.ReferenceEquals()
if (str1 == str2)
Possible Duplicate:
Differences in string compare methods in C#
In .NET there are many string comparison methods, I just want to confirm which one is the best to use considering performance.
string.Equals()
string.Compare()
string.CompareTo()
string.CompareOrdinal()
string.ReferenceEquals()
if (str1 == str2)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
摘自 msdn
string.Equals
确定此实例和指定对象(也必须是 String 对象)是否具有相同的值。
string.Compare
比较两个指定的 String 对象并返回一个整数,指示它们在排序顺序中的相对位置。
string.CompareTo
将此实例与指定对象或字符串进行比较,并返回一个整数,该整数指示此实例在排序顺序中是否与指定对象或字符串位于相同位置之前、之后或出现的位置。
string.CompareOrdinal
通过计算每个字符串中相应 Char 对象的数值来比较两个指定的 String 对象。
字符串相等运算符< /强>
预定义的字符串相等运算符有:
bool 运算符 ==(string x, string y);
布尔运算符 !=(字符串 x, 字符串 y);
当以下任一情况为 true 时,两个字符串值被视为相等:
两个值均为 null。
这两个值都是对字符串实例的非空引用,这些实例在每个字符位置具有相同的长度和相同的字符。
字符串相等运算符比较字符串值而不是字符串引用。当两个单独的字符串实例包含完全相同的字符序列时,字符串的值相等,但引用不同。如第 7.9.6 节中所述,引用类型相等运算符可用于比较字符串引用而不是字符串值。
Ripped from msdn
string.Equals
Determines whether this instance and a specified object, which must also be a String object, have the same value.
string.Compare
Compares two specified String objects and returns an integer that indicates their relative position in the sort order.
string.CompareTo
Compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String.
string.CompareOrdinal
Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.
String equality operators
The predefined string equality operators are:
bool operator ==(string x, string y);
bool operator !=(string x, string y);
Two string values are considered equal when one of the following is true:
Both values are null.
Both values are non-null references to string instances that have identical lengths and identical characters in each character position.
The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in Section 7.9.6, the reference type equality operators can be used to compare string references instead of string values.