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
.
Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method.
Using String.substring() method. You can supply both a start and an end index, or just a start index. When using both a start index and an end index, you get that section of string — the substring — including the character at the start index, but not the character at the end index. For example, "hello".
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.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With