在c#中比较字符串是非常简单的。事实上有几种方法可以做到这一点。我在下面列出了一些。我好奇的是它们之间的区别,以及什么时候应该使用其中一种?是否应该不惜一切代价避免?还有其他我没有列出的吗?
string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
(注:我在这个例子中寻找平等,不小于或大于,但也可以自由评论)
使用. equals,你还可以获得StringComparison选项。对于忽略大小写和其他东西非常方便。
顺便说一句,这将计算为假
string a = "myString";
string b = "myString";
return a==b
因为==比较a和b(它们是指针)的值,只有当指针指向内存中的同一个对象时,这个函数才会求值为true。. equals解引用指针并比较指针上存储的值。
a = (b)在这里为真。
如果把b改成:
b = "MYSTRING";
那么a = (b)是假的,但是
a.Equals(b, StringComparison.OrdinalIgnoreCase)
是正确的
a.CompareTo(b) calls the string's CompareTo function which compares the values at the pointers and returns <0 if the value stored at a is less than the value stored at b, returns 0 if a.Equals(b) is true, and >0 otherwise. However, this is case sensitive, I think there are possibly options for CompareTo to ignore case and such, but don't have time to look now.
As others have already stated, this would be done for sorting. Comparing for equality in this manner would result in unecessary overhead.
我确定我遗漏了一些东西,但我认为如果你需要更多细节,这些信息应该足够开始试验了。
正如Ed所说,CompareTo用于排序。
然而,. equals和==之间是有区别的。
==本质上解析为以下代码:
if(object.ReferenceEquals(left, null) &&
object.ReferenceEquals(right, null))
return true;
if(object.ReferenceEquals(left, null))
return right.Equals(left);
return left.Equals(right);
原因很简单,下面的代码会抛出异常:
string a = null;
string b = "foo";
bool equal = a.Equals(b);
而下面这些则不会:
string a = null;
string b = "foo";
bool equal = a == b;