Java Reference
In-Depth Information
The second version of the substring() method enables you to extract a substring from a string by spe-
cifying the index positions of the first character in the substring and one beyond the last character of the
substring as arguments to the method. With the variable place being defined as before, the following state-
ment results in the variable segment being set to the string "ring" :
String segment = place.substring(7, 11);
NOTE With either version of the substring() method, an exception is thrown if you specify
an index that is outside the bounds of the string. As with the charAt() method, the sub-
string() method throws IndexOutOfBoundsException if the index value is not valid.
You can see how substring() works with a more substantial example.
TRY IT OUT: Word for Word
You can use the indexOf() method in combination with the substring() method to extract a sequence
of substrings that are separated by spaces in a single string:
public class ExtractSubstrings {
public static void main(String[] args) {
String text = "To be or not to be";
// String to be
int count = 0;
// Number of
char separator = ' ';
// Substring
// Determine the number of substrings
int index = 0;
do {
// Increment
substrings count
// Move past last
index = text.indexOf(separator, index);
} while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count];
// Allocate for
index = 0;
// Substring start
Search WWH ::

Custom Search