The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Comparing Strings and Portions of Strings

The String class has several methods for comparing strings and portions of strings. The following table lists these methods.

*Methods in the String Class for Comparing Strings
Method Description
boolean endsWith(String)
boolean startsWith(String)
boolean startsWith(String, int)
Returns true if this string ends with or begins with the substring specified as an argument to the method. The integer argument, when present, indicates the offset within the original string at which to begin looking.
int compareTo(String)
int compareTo(Object)**
int compareToIgnoreCase(String)**
Compares two strings lexicographically and returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument. The Object argument is converted to a string before the comparison takes place. The com-pareToIgnoreCase method ignores case; thus, a and A are considered equal.
boolean equals(Object)
boolean equalsIgnoreCase(String)
Returns true if this string contains the same sequence of characters as the argument. The Object argument is converted to a string before the comparison takes place. The equalsIgnoreCase method ignores case; thus, a and A are considered equal.
boolean regionMatches(int, String, int, int)
boolean regionMatches(boolean, int, String, int, int)
Tests whether the specified region of this string matches the specified region of the String argument. The boolean argument indicates whether case should be ignored; if true, the case is ignored when comparing characters.
* Methods marked with ** were added to the String class for Java 2 SDK 1.2.

The following program, RegionMatchesDemo, uses the regionMatches method to search for a string within another string:

public class RegionMatchesDemo {
	public static void main(String[] args) {
		String searchMe = "Green Eggs and Ham";
		String findMe = "Eggs";
		int len = findMe.length();
		boolean foundIt = false;
		int i = 0;
		while (!searchMe.regionMatches(i, findMe, 0, len)) {
			i++;
			foundIt = true;
		}
		if (foundIt) {
			System.out.println(searchMe.substring(i, i+len));
		}
	}
}
The output from this program is Eggs.

The program steps through the string referred to by searchMe one character at a time. For each character, the program calls the regionMatches method to determine whether the substring beginning with the current character matches the string for which the program is looking.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.