THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The compareTo method is useful for creating an internal canonical ordering of strings. A binary search, for
example, requires a sorted list of elements, but it is unimportant that the sorted order be local language order.
Here is a binary search lookup method for a class that has a sorted array of strings:


private String[] table;


public int position(String key) {
int lo = 0;
int hi = table.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cmp = key.compareTo(table[mid]);
if (cmp == 0) // found it!
return mid;
else if (cmp < 0) // search the lower part
hi = mid - 1;


else // search the upper part
lo = mid + 1;
}
return -1; // not found
}


This is the basic binary search algorithm. It first checks the midpoint of the search range to determine whether
the key is greater than, equal to, or less than the element at that position. If they are the same, the element has
been found and the search is over. If the key is less than the element at the position, the lower half of the range
is searched; otherwise, the upper half is searched. Eventually, either the element is found or the lower end of
the range becomes greater than the higher end, in which case the key is not in the list.


In addition to entire strings, regions of strings can also be compared for equality. The method for this is
regionMatches, and it has two forms:


public booleanregionMatches(int start, String other, int
ostart, int count)

Returns true if the given region of this String has the same Unicode
characters as the given region of the string other. Checking starts in this
string at the position start, and in the other string at position ostart.
Only the first count characters are compared.

public booleanregionMatches(boolean ignoreCase, int start,
String other, int ostart, int count)

This version of regionMatches behaves exactly like the previous one, but
the boolean ignoreCase controls whether case is significant.

For example:


class RegionMatch {
public static void main(String[] args) {
String str = "Look, look!";
boolean b1, b2, b3;


b1 = str.regionMatches(6, "Look", 0, 4);
b2 = str.regionMatches(true, 6, "Look", 0, 4);
b3 = str.regionMatches(true, 6, "Look", 0, 5);


System.out.println("b1 = " + b1);

Free download pdf