开发者

String comparison equivalents

I believe these 2 lines are equivalent but after running into a strange issue I no longer believe this to be the case.

String mimeType = context.Request.ContentType;
(String.Compare("text/xml", mimeType, true) == 0))

is the same as :

context.Request.ContentType.ToLower().Equals("text/xml")

Are their implementations in the CLR any diffe开发者_如何学Pythonrent?


They are not equivalent, and ToLower/ToUpper may have some localization issues. The way to compare two strings without case-sensitivity (considering one of the strings may be null, which is why I don't like the str1.Equals method) is the static String.Equals method:

bool areEqual = String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);


They are not completely equivalent; see here.

Here is the correct way to do a case insensitive comparison:

bool areSame = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);

This way will also be more efficient becasue it doesn't allocate a separate string for the lowercase copy.


In addition to the other answers (@SLaks, @Serhio), I also feel obligated to point out that .ToLower() generates another string. Compare does not as far as I know. Excessive string generation in an app can come back to bite you in terms of memory usage and performance if it is in frequently called code.


the implementation of Compare(string, string, boolean) in .NET:

public static int Compare(string strA, string strB, bool ignoreCase)
{
    if (ignoreCase)
    {
        return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
    }
    return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
}

and Equals

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public bool Equals(string value)
{
    if ((value == null) && (this != null))
    {
        return false;
    }
    return EqualsHelper(this, value);
}

So, is NOT the same thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜