Java Reference
In-Depth Information
int endIndex = 0;
// Substring end
index
for(int i = 0; i < count; ++i) {
endIndex = text.indexOf(separator,index); // Find next
separator
if(endIndex == -1) {
// If it is not found
subStr[i] = text.substring(index);
// extract to the end
} else {
// otherwise
subStr[i] = text.substring(index, endIndex);
// to end index
}
index = endIndex + 1;
// Set start for
next cycle
}
// Display the substrings
for(String s : subStr) {
// For each string
in subStr
System.out.println(s);
// display it
}
}
ExtractSubstrings.java
When you run this example, you should get the following output:
To
be
or
not
to
be
How It Works
After setting up the string text to be segmented into substrings, a count variable to hold the number of
substrings, and the separator character, separator , the program has three distinct phases:
1. The first phase counts the number of substrings by using the indexOf() method to find separators.
The number of separators is always one less than the number of substrings. By using the do-while
loop, you ensure that the value of count is one more than the number of separators because there is
always one loop iteration for when the separator is not found.
2. The second phase extracts the substrings in sequence from the beginning of the string and stores
them in an array of String variables that has count elements. A separator follows each substring from
the first to the penultimate so you use the version of the substring() method that accepts two index
arguments for these. The last substring is signaled by a failure to find the separator character when
endIndex is −1. In this case you use the substring() method with a single argument to extract the
substring through to the end of the string text .
Search WWH ::




Custom Search