A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© みぎ 中级黑马   /  2015-3-19 16:50  /  839 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在JDK6中,这个方法只会在标识现有字符串的字符数组上 给一个窗口来表示结果字符串,但是不会创建一个新的字符串对象。如果需要创建个新字符串对象,可以这样在结果后面+一个空的字符串:
  1. str.substring(m, n) + ""
复制代码

Oracle JDK7中的substring()方法会创建一个新的字符数组,而不用之前存在的。
substring() in JDK 6:
  1. //JDK 6
  2. String(int offset, int count, char value[]) {
  3.     this.value = value;
  4.     this.offset = offset;
  5.     this.count = count;
  6. }

  7. public String substring(int beginIndex, int endIndex) {
  8.     //check boundary
  9.     return  new String(offset + beginIndex, endIndex - beginIndex, value);
  10. }
复制代码
substring() in JDK 7:
  1. //JDK 7
  2. public String(char value[], int offset, int count) {
  3.     //check boundary
  4.     this.value = Arrays.copyOfRange(value, offset, offset + count);
  5. }

  6. public String substring(int beginIndex, int endIndex) {
  7.     //check boundary
  8.     int subLen = endIndex - beginIndex;
  9.     return new String(value, beginIndex, subLen);
  10. }
复制代码


参考:http://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马