substring()或者substr()是大部分主流语言所支持的,同时对字符串的操作是编程中最频繁的操作,当然对截取字符串也是最常用操作之一。所以今天就讨论一下subtring()。
以JAVA举例,在JAVA中我们看看系统提供的substring()有什么问题?
我们首先看看JDK中substring()的源码:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
这段代码主要的这行:new String(offset + beginIndex, endIndex - beginIndex, value)
我们在进这个String构造方法,看看它做了什么?
// Package private constructor which shares value array for speed.
S

substring()在某些编程语言中可能导致内存泄漏,因为新字符串对象引用了原始字符串的char数组。JDK7已解决此问题,但可以通过创建新String对象或自定义substring()函数来避免。本文探讨了两种解决方法,并提到了PHP的substr()按字节截取可能产生的乱码问题,指出在需要按字节截取时需自定义函数。
最低0.47元/天 解锁文章
906





