Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.
To achieve this, we use the substring() method like this:
string.substring(startIndex, endIndex);
This is called slicing a string. It returns the substring from startIndex to endIndex.
Here is an example:
String language = "JavaScript";
String substring = language.substring(2, 6);
System.out.println(substring); // Output: "vaSc"
System.out.println(language); // Output: "JavaScript"
The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.
The substring will not include the character at endIndex. You can see in our example that the character at index 2 (v) was included while the character at index 6 (r) was excluded.
Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.
If you omit the endIndex, the slice() extracts to the end of the string:
String language = "JavaScript";
String substring = language.substring(4);
System.out.println(substring); // Output: "Script"
Assignment
Follow the Coding Tutorial and let's slice some strings!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
