String s="abcdef";
s.charAt(6);//抛出异常
s.substring(6);//返回空字符串
s.substring(7);//抛出异常
为什么会这样?charAt方法和substring方法具体是怎么运行的?
期待大侠解疑
s.charAt(6);//抛出异常
s.substring(6);//返回空字符串
s.substring(7);//抛出异常
为什么会这样?charAt方法和substring方法具体是怎么运行的?
期待大侠解疑
subString 是从1开始....
public char charAt(int index)返回指定索引处的 char 值。索引范围为从 0 到 length() - 1。序列的第一个 char 值在索引 0 处,第二个在索引 1 处,依此类推,这类似于数组索引。
如果索引指定的 char 值是代理项,则返回代理项值。 substring
public String substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。参数:
beginIndex - 开始处的索引(包括)。
返回:
指定的子字符串。 substring
public String substring(int beginIndex,
int endIndex)返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,一直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
示例: "hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
参数:
beginIndex - 开始处的索引(包括)。
endIndex - 结束处的索引(不包括)。
返回:
指定的子字符串。
s.charAt(5);
s.substring(5);
s.substring(5);
public String substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。
例如: "unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
参数:
beginIndex - 开始处的索引(包括)。
返回:
指定的子字符串。
抛出:
IndexOutOfBoundsException - 如果 beginIndex 为负或大于此 String 对象的长度。看看api ,下标越界
示例: "unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)注意红色部分,字符串的末尾,也就是说是最后一个字符后面
String s="abcdef";
也就是紧跟'f'后面那个位置,其实是个空值,如果再往后面一个字符那就是null了
意思是返回索引为6的那个char,你提供的这个字符串的最大索引为5,所以抛出索引超越了边界异常
同理
s.substring(6); s.substring(7)也是这个错误