Java Reference
In-Depth Information
This solution gives us a second version of the method:
public static String firstWord(String s) {
int start = 0;
int stop = 0;
while (stop < s.length() && s.charAt(stop) != ' ') {
stop++;
}
return s.substring(start, stop);
}
But remember that we assumed that the first word starts at position 0. That won't
necessarily be the case. For example, if we pass a string that begins with several
spaces, this method will return an empty string. We need to modify the code so that it
skips any leading spaces. Accomplishing that goal requires another loop. As a first
approximation, we can write the following code:
int start = 0;
while (s.charAt(start) == ' ') {
start++;
}
This code works for most strings, but it fails in two important cases. The loop test
assumes we will find a nonspace character. What if the string is composed entirely of
spaces? In that case, we'll simply run off the end of the string, generating a
StringIndexOutOfBoundsException . And what if the string is empty to begin
with? We'll get an error immediately when we ask about s.charAt(0) , because
there is no character at index 0 .
We could decide that these cases constitute errors. After all, how can you return
the first word if there is no word? So, we could document a precondition that the
string contains at least one nonspace character, and throw an exception if we find that
it doesn't. Another approach is to return an empty string in these cases.
To deal with the possibility of the string being empty, we need to modify our loop
to incorporate a test on the length of the string. If we add it at the end of our while
loop test, we get the following code:
int start = 0;
while (s.charAt(start) == ' ' && start < s.length()) {
start++;
}
But this code has the same flaw we saw before. It is supposed to prevent problems
when start becomes equal to the length of the string, but when this situation occurs,
a StringIndexOutOfBoundsException will be thrown before the computer reaches
 
Search WWH ::




Custom Search