100个java开发只有1人见过的方法,jdk中自带实用equalsIgnoreCase方法,特别适合爬虫,也许你没有见过

今天在看源码的时候看到了一个很实用但是却几乎没有人用的一个方法,equalsIgnoreCase ,看了一遍源码后,总结了一下这个方法的用法:用来比较两个字符串,并且忽略其大小的情况,判断被比较的字符串中是否包含其中的字符串,这个可以广泛的运用到java的爬虫中,可以节省很多代码量和效率。
首先来看看源码,先进行字符串的判空,然后进行一个regionmatches的比较,

public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true            : (anotherString != null)
                && (anotherString.value.length == value.length)
                && regionMatches(true, 0, anotherString, 0, value.length);
    }

下面是regionMatches中的源码,这个方法才是真正的底层,看完了就懂了。

public boolean regionMatches(boolean ignoreCase, int toffset,
            String other, int ooffset, int len) {
        char ta[] = value;
        int to = toffset;
        char pa[] = other.value;
        int po = ooffset;
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {
            return false;
        }
        while (len-- > 0) {
            char c1 = ta[to++];
            char c2 = pa[po++];
            if (c1 == c2) {
                continue;
            }
            if (ignoreCase) {
                // If characters don't match but case may be ignored,
                // try converting both characters to uppercase.
                // If the results match, then the comparison scan should
                // continue.
                char u1 = Character.toUpperCase(c1);
                char u2 = Character.toUpperCase(c2);
                if (u1 == u2) {
                    continue;
                }
                // Unfortunately, conversion to uppercase does not work properly
                // for the Georgian alphabet, which has strange rules about case
                // conversion.  So we need to make one last check before
                // exiting.
                if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                    continue;
                }
            }
            return false;
        }
        return true;
    }

再举个使用的场景例子:判定字符串出现的次数

public static void main(String[] args) {			 
			/**@author yemaomao
			 * @param 判断字符串出现的次数
			 */ 			 
				int number = 0;
				String str = "fdafdadfadf";
				for (int i = 0; i < str.length(); i++) {
					if (str.regionMatches(i, "da", 0, 2)) {
						number++;
					}
				}				
				System.out.println(number);
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会飞奇迹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值