substring index range
Code:
public class Test {
public static void main(String[] args) {
String str = "University";
System.out.println(str.substring(4, 7));
}
}
Output: ers
I do not really understand how the substring method works. Does the index start at 0? If I start with 0, e
is at index 4 but char i
is at 7 so the output would be ersi
.
0: U
1: n
2: i
3: v
4: e
5: r
6: s
7: i
8: t
9: y
Start index is inclusive
End index is exclusive
Javadoc link
Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end
.
To make life easier for substring
operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
↑ ↑
start end --> range of "E R S"
Quoting the docs:
The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
. Thus the length of the substring isendIndex-beginIndex
.
See the javadoc. It's an inclusive index for the first argument and exclusive for the second.
Like you I didn't find it came naturally. I normally still have to remind myself that
-
the length of the returned string is
lastIndex - firstIndex
that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception
so
"University".substring(6, 10)
returns the 4-character string "sity"
even though there is no character at position 10.
public String substring(int beginIndex, int endIndex)
beginIndex
—the begin index, inclusive.
endIndex
—the end index, exclusive.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3, 8));
}
}
Output: "lo Wo"
From 3 to 7 index.
Also there is another kind of substring()
method:
public String substring(int beginIndex)
beginIndex
—the begin index, inclusive.
Returns a sub string starting from beginIndex
to the end of the main String.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3));
}
}
Output: "lo World"
From 3 to the last index.