java substring实现_java字符串subString的实现

1 功能: substring (beginIndex,endIndex),取字符串beginIndex和endIndex之间的字符,缺少第二个参数时,取beginIndex到字符串末尾的字符。

2 实现方法在String 类里

public String substring(int beginIndex, int endIndex) {

if (beginIndex < 0) {

throw new StringIndexOutOfBoundsException(beginIndex);

}

if (endIndex > value.length) {

throw new StringIndexOutOfBoundsException(endIndex);

}

int subLen = endIndex - beginIndex;

if (subLen < 0) {

throw new StringIndexOutOfBoundsException(subLen);

}

return ((beginIndex == 0) && (endIndex == value.length)) ? this

: new String(value, beginIndex, subLen);

}

那么new String(value, beginIndex, subLen) 是怎么实现的呢?

public String(char value[], int offset, int count) {

if (offset < 0) {

throw new StringIndexOutOfBoundsException(offset);

}

if (count < 0) {

throw new StringIndexOutOfBoundsException(count);

}

// Note: offset or count might be near -1>>>1.

if (offset > value.length - count) {

throw new StringIndexOutOfBoundsException(offset + count);

}

this.value = Arrays.copyOfRange(value, offset, offset+count);

}

public static char[] copyOfRange(char[] original, int from, int to) {

int newLength = to - from;

if (newLength < 0)

throw new IllegalArgumentException(from + " > " + to);

char[] copy = new char[newLength];

System.arraycopy(original, from, copy, 0,

Math.min(original.length - from, newLength));

return copy;

}

追踪发现,是本地方法,调用的是c++实现的底层函数

public static native void arraycopy(Object src, int srcPos,

Object dest, int destPos,

int length);

有意思的就要来了,c++代码:else代码意义:防止新的内容覆盖掉原来的内容

static void pd_conjoint_oops_atomic(oop* from, oop* to, size_t count) {

// Do better than this: inline memmove body NEEDS CLEANUP

if (from > to) {

while (count-- > 0) {

// Copy forwards

*to++ = *from++;

}

} else {

from += count - 1;

to += count - 1;

while (count-- > 0) {

// Copy backwards

*to-- = *from--;

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值