Java Reference
In-Depth Information
text = text.toLowerCase(); // Convert string to lower case
This statement replaces the original string with the lower case equivalent. If you wanted to retain the original,
you could store the lower case string in another variable of type String . For converting strings to upper
case, the class String also has a method toUpperCase() which is used in the same way.
The if expression checks for any of the vowels by OR ing the comparisons for the five vowels together.
If the expression is true we increment the vowels count. To check for a letter of any kind we use the
isLetter() method in the class Character , and accumulate the total letter count in the variable
letters . This will enable us to calculate the number of consonants by subtracting the number of
vowels from the total number of letters. 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 blanks in the text, you could compare for a blank character. After the for loop
ends, we just output the results.
Searching Strings for Characters
There are two methods, available to you in the class String , that will search a string, indexOf() and
lastIndexOf() . Both of these come 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() will search the contents of the string text forwards from the beginning, and return
the index position of the first occurrence of ' a '. If ' a ' is not found, the method will return the value -1.
This is characteristic of both the 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 important that you check the index value returned for -1 before you use it
to index a string, otherwise you will 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 backwards, starting with the last character in the string. The variable
index will therefore contain the index position of the last occurrence of ' a ', or -1 if it is not found.
Search WWH ::




Custom Search