前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >jdk源码系列:String判断两个字符串是否相等以及忽略大小写相等的实现

jdk源码系列:String判断两个字符串是否相等以及忽略大小写相等的实现

作者头像
爱明依
发布2019-04-26 12:58:05
8000
发布2019-04-26 12:58:05
举报
文章被收录于专栏:爱明依爱明依

版权声明:欢迎关注博主公众号:矿洞程序员 https://blog.csdn.net/qq_32423845/article/details/89336144

源码如下:

核心思路:取到每一个字符,比较如果全部相等则返回true

代码语言:javascript
复制
public boolean equals(Object anObject){
		if(this==anObject){
			return true;
		}
		if(anObject instanceof String){
			String anotherString=(String)anObject;
			int n=value.length;
			if(n==anObject.value.length){
				char v1[]=value;
				char v2[]=anotherString.value;
				int i=0;
				while(n--!=0){
					if(v1[i]!=v2[i])
						return false;
					    i++;
				}
				return true;
			}
		}
		return false;
	}
代码语言:javascript
复制
public boolean equalsIgnoreCase(String anotherString){
		return (this==anotherString)?true:(anotherString!=null)&&(anotherString.value.length==value.length)&&
		regionMatches(true,0,anotherString,0,value.length);
	}
	
	 
	
	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=offset;
		//Note:toOffset ,offset,or len might be near -1>>1
		if((ooffset<0) || (toOffset<0)|| (toffset>(long)value.length-len) || (offset>(long)other.value.length-len)){
			return false;
		}
		while(len-->0){
			char c1=ta[to++];
			char c2=pa[po++];
			if(c1==c2){
				continue;
			}
			if(ignoreCase){
				char u1=Character.toUpperCase(c1);
				char u2=Character.toUpperCase(c2);
				if(u1=u2){
					continue
				}
				if(Character.toLowerCase(u1)==Character.toLowerCase(u2)){
					continue;
				}
			}
			return false;
 		}
		return true;
	}

核心思路:字符比较。如果字符转为大写或者小写。相等 则相等

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年04月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档