String源码总结

1.indexof 方法

if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}

char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);

for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}

/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);

if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;

这个方法中是进行暴力匹配 通过一个while循环和一个for循环来进行匹配找到字符串的索引
注意:while for循环判断 没有循环体 true的话就再一次判断 false跳出循环

2.intern() string对象 调用这个方法的时候 判断有没有常量池中有没有这个字符串 没有就加入到常量池
主要是做内存优化的;
3codePointAt(index) 这个方法返回的是一个int值 eg: a->97

4.equals
这个方法中的
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.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;

中间while 循环的循环条件是 n--!=0 为什么 呢 为什么不直接用正面的i++<n

5.regionMatches
str.regionMatches(true, 0, anotherString, 0, length);
第一个参数 表示忽略大小写
第二个 表示 str 从0位置开始比较
第三 另一个字符串
四 另一个字符串从0位置开始
五 比较的长度
6.hashcode
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
系数31
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值