关于JAVA str.substring(int beginIndex,endIndex)的问题

我看书上说 str.substring(int beginIndex,endIndex)这个代码是从字符串某一索引位置开始截取至某一索引位置结束的子串。我的代码如下:

public class Substring {
public static void main(String[] args) {
String str="hello word";
String size=str.substring(0,3);
System.out.println(size);
}
}
这个最后输出是hel,可是我怎么觉得应该是hell?
0是h,3是l(第二个l),这样截取下来的话不是应该是hell吗

你那本书有问题吧。第二个参数是长度,不是结束字符串下标
see this :http://blog.csdn.net/tony8829/article/details/6448582

输出hel是正确的。
这个API的介绍如下:
return a new string consisting of all code units from beginIndex until the end of the string or until endIndex - 1.
所以,这个API本来就是要返回从beginIndex到endIndex-1范围内的字符串,或者是返回从beginIndex到字符串结尾的字符串。

参考 你了解Java中String的substring函数吗?
最终是返回new String(offset + beginIndex, endIndex - beginIndex, value);而offset是存储的第一位,也就是1,也就是说从第1位,取3个字符

简单来说这个方法包括前面字符的下标,不包括后面字符的下标

第二个参数是长度而不是结束索引。

这些基础函数,看 API文档说明即可:

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Examples:

"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

说是第二个参数是长度的,多看看api吧~~再不信去自己去试试str.(5,6)这种,看看是截取一个字符出来,还是6个字符~

看来你没理解函数意义。
0表示,从第一位开始截取。3表示截取三个字符,当然就是hel了。(0,4)才是hell

java里面的范围 一般都是包头不包尾

书上的讲的不对,应该是
String.substring(int beginIndex, int length)
建议以后碰到类似的问题,就看下jdk源码,源码的可读性还是很高的。共勉

霜之哀伤是对的,加一句,之所以第二参数设置成lastindex +1是因为如果你做
str.substring(0, str.length())可以拿到整个字符串,如果第二参数是最后一个下标,就需要写成
str.substring(0, str.length() - 1)
这样就会非常奇怪

一句话:在java中牵扯到区间问题,大部分都是左闭右开的,所以这个也不例外,下标包含0而不包含3,只能到3-1=2那里,还有一个问题就是,String字符串和数组的元素一样,下标都是从0开始的,即0表示第一个字母