commons-lang3-3.6.jar的StringUtils中的equals()和equalsIgnoreCase()有什么区别?

时间:2018-06-29 14:44:38

标签: java equals apache-commons-lang3

当我使用这两种方法时,我想知道它们的区别,以及equalsIgnoreCase()如何忽略两个String的情况。但是我什至没有找到源代码的区别,只是代码的顺序不同。 谁能帮助我分析源代码的差异,以及它如何忽略大小写?谢谢。 这是源代码:

public static boolean equals(CharSequence cs1, CharSequence cs2) {
    if (cs1 == cs2) {
        return true;
    } else if (cs1 != null && cs2 != null) {
        if (cs1.length() != cs2.length()) {
            return false;
        } else {
            return cs1 instanceof String && cs2 instanceof String ? cs1.equals(cs2) : CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length());
        }
    } else {
        return false;
    }
}

public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2) {
    if (str1 != null && str2 != null) {
        if (str1 == str2) {
            return true;
        } else {
            return str1.length() != str2.length() ? false : CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length());
        }
    } else {
        return str1 == str2;
    }
}

4 个答案:

答案 0 :(得分:0)

equalsIgnoreCase执行以下测试:

  1. 字符串是否为空?如果是这样,请返回str1 == str2
  2. str1 == str2是吗?如果是这样,则返回true
  3. 字符串的长度是否不同?如果是这样,则返回false
  4. 使用regionMatches的{​​{1}}方法和第二个参数CharSequenceUtils设置为true来比较两者。

您可以找到ignoreCase here的源代码。如果regionMatches设置为true,则该函数在比较字符时会大写字符。

相反,ignoreCaseequals的false调用regionMatches,这将导致ignoreCase不对字符进行大写。

答案 1 :(得分:0)

equalsIgnoreCase(...)忽略大小写(大写或小写)。 。

"HELLO".equalsIgnoreCase("hello")

是真的。

答案 2 :(得分:0)

区别在于方法CharSequenceUtils.regionMatches中。第二个参数是ignoreCase

static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
        CharSequence substring, int start, int length)    {
    if (cs instanceof String && substring instanceof String) {
        return ((String) cs).regionMatches(ignoreCase, thisStart, ((String) substring), start, length);
    } else {
        // TODO: Implement rather than convert to String
        return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
    }
}

答案 3 :(得分:0)

等于,您会看到字符串相等:示例:

if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
    filterContext.HttpContext.Response.StatusCode = 
    (int)System.Net.HttpStatusCode.Unauthorized;

    filterContext.HttpContext.Response.ContentType = "application/json";



    filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    string json = serializer.Serialize(new { IsUnauthenticated = true });
    filterContext.HttpContext.Response.Write(json);

    filterContext.HttpContext.Response.End();
}

在equalsIgnoreCase中,顾名思义,是在不区分大小写的情况下尝试比较字符串相等性:

 StringUtils.equals("abc", "abc") = true
 StringUtils.equals("abc", "ABC") = false

From Apache Doc.