String类的subString(i)方法(基于jdk 1.9)
2024-08-24 08:23:54
只有一个参数的;
String str = new String("ABCD");
System.out.println("str="+str.substring(1));
进入substring()
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = length() - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
if (beginIndex == 0) {
return this;
}
return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
: StringUTF16.newString(value, beginIndex, subLen);
}
分析:
- 当 beginIndex < 0或者 beginIndex > length的时候,直接抛出越界异常;
- 当 beginIndex 就是0 的时候,返回原字符串;
- 最后判断是 isLatin1是否满足,进入StringLatin1/StringUTF16;
进入StringLatin1.newString
public static String newString(byte[] val, int index, int len) {
return new String(Arrays.copyOfRange(val, index, index + len),
LATIN1);
}
分析:
- byte[] val : 也就是str的构成数组,{A,B,C,D};
- int index:beginIndex = 1;
- int len :subLen = 4 -1 = 3;
再调用 Arrays.copyOfRange
public static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
分析:
- byte[] original:还是{A,B,C,D};
- int from : index = 1;
- int to :index + len = 1 + 3 = 4 (实际就是str的长度);
- 该方法定义了一个新的数组,长度为:length - beginIndex = 3;
最后调用:
System.arraycopy
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
分析:
- 参数1,src ,源数组 ,传入 original,{A,B,C,D};
- 参数2 ,srcPos 源数组的开始位置,传入 beginIndex = 1;
- 参数3, dest ,目标数组,传入是一个空的 length 为 3的数组;
- 参数4,destPos 目标数组的开始位置,传入 0;
- 参数5,length 需要copy元素的数量,本次调用,传递的是 length - beginIndex = 3(经过最小值判断,仍然等价)
- 结果:
- copy[0] = original[1];
- copy[1] = original[2];
- copy[2] = original[3];
综上,str.subString(i) 实际上是
- 将 str 转成数组 array01,赋值给一个为新的数组 array02,并且array02.length = str.length - i;
- 赋值过程为:array02[0] = array01[i](直到i = array01.length)
- array02转换新的String,并返回;
得出结论:subString(i)返回值是 str的索引位置i,到最大索引(两个索引都包括)
最新文章
- Javascript的二进制数据处理学习 ——nodejs环境和浏览器环境分别分析
- 数据库—SQL语句
- 常用的工具cmd命令
- NOIP 2011 Day 1 部分题解 (Prob#1 and Prob#2)
- OpenERP QWeb模板标签笔记
- vi编辑器选项
- spring接收参数
- python操作Excel读--使用xlrd
- samba错误
- leetcode_question_67 Add Binary
- 【安卓笔记】高速的发展设置界面-----PreferenceActivity
- 使用 IDEA 创建 Maven Web 项目 (三)- 编写一个简单的 WEB 应用
- Android: Toolbar、AppBarLayout
- Selenium常规操作---基于python
- 优化的四个方面,缓存,表结构,索引,SQL语句
- Android状态栏着色
- 第10章 嵌入式Linux 的调试技术
- CF1091E New Year and the Acquaintance Estimation
- Java_myBatis入门写法
- UVALive - 3266 Tian Ji -- The Horse Racing(贪心)