How does .substring() work with two arguments? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How does .substring() work with two arguments?

6th Aug 2019, 10:24 PM
Samuel
Samuel - avatar
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. */
6th Aug 2019, 11:01 PM
Jake
Jake - avatar
0
Nice!
11th Aug 2019, 2:57 PM
Juan Debenedetti
Juan Debenedetti - avatar