Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
TheString
class has several methods for comparing strings and portions of strings. The following table lists these methods.
Methods in the String
Class for Comparing StringsMethod 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 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 compareToIgnoreCase method ignores case; thus, "a" and "A" are considered equal. boolean equals(Object)
boolean equalsIgnoreCase(String)
boolean contentEquals(CharSequence)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. TheequalsIgnoreCase
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. boolean matches(String)
Tests whether this string matches the specified regular expression. For more information on how to use the API for pattern matching, see Regular Expressions. The following program,
RegionMatchesDemo
, uses theregionMatches
method to search for a string within another string:The output from this program ispublic 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)); } } }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.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.