Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
How does .substring() work with two arguments?
2 Answers
+ 2
String s = "hello world";
String sub = s.substring(6,11);
System.out.println(sub);
/*
The arguments are (start,end). Essentially, the string is being converted into a char array, so you will index start and end the same way you would index any array. It will create a new string beginning at the specified start index and all the characters up to but not including the specified end index:
h = 0
e = 1
l = 2
l = 3
o = 4
(space) = 5
w = 6
o = 7
r = 8
l = 9
d = 10
So, if we’re subbing (6,11):
the first argument(start) is inclusive, meaning it will include the character at index 6('w'), the second argument(end) is exclusive, meaning it will not include the character at index 11, but instead the index before it(10, which is 'd') for that reason, you wont get an IndexOutOfBounds Exception for referring to index 11.
*/
0
Nice!