Java Reference
In-Depth Information
equalsIgnoreCase");
}
The compareTo() and compareToIgnoreCase() methods perform a lexico-
graphical comparison of the strings. This comparison is based upon the Unicode value
of each character contained within the strings. The result will be a negative integer if
the string lexicographically precedes the argument string. The result will be a positive
integer if the string lexicographically follows the argument string. The result will be
zero if both strings are lexicographically equal to each other. The following excerpt
from the solution to this recipe demonstrates the compareTo() method:
// Comparison is equal
if (one.compareTo(var1) == 0){
System.out.println("One is equal to var1 using
compareTo()");
}
Inevitably, many applications contain code that must compare strings at some level.
The next time you have an application that requires string comparison, consider the in-
formation discussed in this recipe before you write the code.
3-3. Trimming Whitespace
Problem
One of the strings you are working with contains some whitespace on either end. You
would like to get rid of that whitespace.
Solution
Use the string trim() method to eliminate the whitespace. In the following example,
a sentence is printed including whitespace on either side. The same sentence is then
printed again using the trim() method to remove the whitespace so that the changes
can be seen.
Search WWH ::




Custom Search