Java Reference
In-Depth Information
Finally, the loop code checks for a space by using the isWhitespace() method in the class Character .
This method returns true if the character passed as an argument is a Unicode whitespace character. As
well as spaces, whitespace in Unicode also includes horizontal and vertical tab, newline, carriage return,
and form-feed characters. If you just wanted to count the spaces in the text, you could explicitly compare
for a space character. After the for loop ends, you just output the results.
Searching Strings for Characters
There are two methods available to you in the String class that search a string: indexOf() and lastIn-
dexOf() . Each of these comes in four different flavors to provide a range of search possibilities. The basic
choice is whether you want to search for a single character or for a substring, so let's look first at the options
for searching a string for a given character.
To search a string text for a single character, 'a' for example, you could write:
int index = 0; // Position of character in the string
index = text.indexOf('a'); // Find first index position containing 'a'
The method indexOf() searches the contents of the string text forward from the beginning and return
the index position of the first occurrence of 'a' . If 'a' is not found, the method returns the value −1.
NOTE This is characteristic of both search methods in the class String . They always return
either the index position of what is sought or −1 if the search objective is not found. It is im-
portant that you check the index value returned for −1 before you use it to index a string;
otherwise, you get an error when you don't find what you are looking for.
If you wanted to find the last occurrence of 'a' in the String variable text , you just use the method
lastIndexOf() :
index = text.lastIndexOf('a'); // Find last index position containing 'a'
The method searches the string backward, starting with the last character in the string. The variable index
therefore contains the index position of the last occurrence of 'a' , or −1 if it is not found.
You can now find the first and last occurrences of a character in a string, but what about the ones in the
middle? Well, there's a variation of each of the preceding methods that has a second argument to specify a
“from position” from which to start the search. To search forward from a given position, startIndex , you
would write:
index = text.indexOf('a', startIndex);
This version of the method indexOf() searches the string for the character specified by the first argument
starting with the position specified by the second argument. You could use this to find the first 'b' that
comes after the first 'a' in a string with the following statements:
Search WWH ::




Custom Search