Comparing Strings

   

Often, you need to know when two strings are equal. For example, you might want to compare a string entered by the user to another string in your program or compare data returned by the database for a particular value. There are three general ways you can compare strings:

  • Calling the equals() method

  • Calling the equalsIgnoreCase() method

  • Using the normal comparison operator ==

The equals method returns true when the argument is non-null and the argument string represents the same set of characters as the source string. Otherwise, it returns false. Here's an example:

 String str = "This is a string"; boolean result = str.equals("This is a string"); 

Here, the boolean variable result is equal to true. Because strings of exactly the same set of characters will represent the same reference in memory, you could also do something similar using the comparison, or double-equals, operator:

 String str = "This is a string"; if (str == "This is a string")     result = true; 

This also results in result being true. Remember that for this to be true, it must be exactly the same literal string.

Although these two methods are the easiest ways to compare strings, the String class gives you many other options. The equalsIgnoreCase method compares two strings without regard for upper- or lowercase letters . That is, the following code sets result to false because equals considers the case of the characters in the string:

 String str = "This is a string"; boolean result = str.equals("This is a string"); 

This code fragment, however, sets result to true:

 String str = "THIS IS A STRING"; boolean result = str.equalsIgnoreCase("this is a string"); 

If you want to know more than just whether the strings are equal, you can call on the compareTo method, which returns a value less than zero when the String object is less than the given string, zero when the strings are equal, and greater than zero if the String object is greater than the given string. The comparison is done according to lexicographic ordering. So, this code segment sets result to a value greater than zero because THIS IS A STRING is greater than ANOTHER STRING:

 String str = "THIS IS A STRING"; int result = str.compareTo("ANOTHER STRING"); 

Note

With "Lexicographic ordering," if two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both.

If they have different characters at one or more index positions , then the string whose character at the closest position to has the smaller value compared to the string at the same index position, as determined by using the < operator, lexicographically precedes the other string.

If there is no index position at which they differ , then the shorter string lexicographically precedes the longer string.


In the following comparison, however, result is set to a value less than zero, because THIS IS A STRING is less than ZZZ ANOTHER STRING:

 String str = "THIS IS A STRING"; int result = str.compareTo("ZZZ ANOTHER STRING"); 

Finally, the following comparison results in zero because the strings are equal:

 String str = "THIS IS A STRING"; int result = str.compareTo("THIS IS A STRING"); 

C and C++ programmers should be familiar with this form of string comparison.

The regionMatches method is another comparison method that you can use to compare part of one string with part of another. Here's an example:

 String str = "THIS IS A STRING"; boolean result = str.regionMatches(10, "A STRING", 2, 6); 

The regionMatches() method's four arguments are as follows :

  • Where to start looking in the source string

  • The string to compare to

  • The location in the comparison string at which to start looking

  • The number of characters to compare

The preceding example sets result to true. In this case, Java starts looking in THIS IS A STRING at the tenth character (starting from 0), which is the S in STRING. Java also starts its comparison at the second character of the given string A STRING, which is also the S in STRING. Java compares six characters starting at the given offsets, which means it is comparing STRING with STRING, a perfect match.

There's also a version of regionMatches that is not case sensitive. The following example sets result to true:

 String str = "THIS IS A STRING"; boolean result = str.regionMatches(true, 10, "A string", 2, 6); 

The first argument in this version of regionMatches is a boolean value indicating whether the comparison should not be case sensitive. A parameter value of true tells the method to ignore the case of the characters. A value of false tells the method to use a case-sensitive comparison. This is the same as you get with the four-argument version of regionMatches.

Listing 8.2 is an application that gives you a chance to experiment with the compareTo method. When you run the application, you need to provide two strings that will be compared against one another.

Listing 8.2 StringCompareExample.java ” An Application Comparing Two Strings
 public class StringCompareExample {   // Default Constructor   public StringCompareExample()   {     super();   }   // Method that actually performs the comparison   public int compareStrings( String str1, String str2 )   {     return str1.compareTo( str2 );   }   // Main Method   public static void main( String[] args )   {     if ( args.length != 2 )     {       System.out.println(           "Usage: java StringCompareExample <String1> <String2>" ); System.exit( 0 );     }     // Create an instance of the example     StringCompareExample example = new StringCompareExample();     // Get the strings passed in from the command line     String str1 = args[0];     String str2 = args[1];     // Inform the user what is going on     System.out.println(         "Comparing string: '" + str1 + "'with: '" + str2 + "'");     // perform the comparison     int result = example.compareStrings( str1, str2 );     // check the result for a negative     if ( result < 0 )     {       System.out.println( "String 1 is less than String 2" );     }     else if ( result > 0 )     {       System.out.println( "String 1 is greater than String 2" );     }     else     {       System.out.println( "String 1 and String 2 are equal" );     }   } } 

Here is the output when you run the example from Listing 8.2:

 C:\jdk1.3se_book\classes>java StringCompareExample "All good things" "Must come to an End" Comparing string: 'All good things'with: 'Must come to an End' String 1 is less than String 2 C:\jdk1.3se_book\classes>java StringCompareExample "All good things" "All good people" Comparing string: 'All good things'with: 'All good people' String 1 is greater than String 2 C:\jdk1.3se_book\classes> 
   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net