您的位置:首页 > 编程语言 > Java开发

java字符串subString的实现

2016-05-04 18:48 676 查看
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
:<span style="color:#009900;"> new String(value, beginIndex, subLen)</span>;
}


那么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 = <span style="color:#009900;">Arrays.copyOfRange(value, offset, offset+count);</span>
}


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];
<span style="color:#009900;"> System.arraycopy</span>(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 {
<span style="color:#009900;">from += count - 1;
to   += count - 1;
while (count-- > 0) {
// Copy backwards
*to-- = *from--;</span>
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: