Sunday, 17 July 2016

String comparison in Java

In String class there are number of methods provided to compare the Strings or the portion of the strings.

Some of the most used are mentioned here -

startsWith() and endsWith() methods

  • boolean startsWith(String prefix) - Returns true if this string begins with the substring specified as an argument to the method.
  • boolean startsWith(String prefix, int offset) - Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.
  • boolean endsWith(String suffix) - Returns true if this string ends with the substring specified as an argument to the method.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  // Should be true
  System.out.println(str.startsWith("This"));
  // test start at index 10, so returns true
  System.out.println(str.startsWith("test", 10));
  
  // returns false
  System.out.println(str.endsWith("test"));
  // returns true
  System.out.println(str.endsWith("test string"));
  // returns true
  System.out.println(str.endsWith("string")); 
 }
}

Output

true
true
false
true
true

equals() and equalsIgnoreCase() methods

  • boolean equals(Object anObject) - Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
  • boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  String str1 = new String("This");
  System.out.println("String for comparison -- " + str.substring(0, 4));
  // Should be true
  System.out.println(str.substring(0, 4).equals("This"));
  // will be false, equals is case sensitive
  System.out.println(str.substring(0, 4).equals("this"));
  
  // returns true, case is ignored
  System.out.println(str.substring(0, 4).equalsIgnoreCase("this"));
  // returns true
  System.out.println(str1.equalsIgnoreCase("this"));
 }
}

Output

String for comparison -- This
true
false
true

Here original string is substringed to give a part of the String (“This”). That part is then used for comparison. Even when a new String is created which will have different reference equals or equalsIgnoreCase will return true as content is matched here not reference.

compareTo() and compareToIgnoreCase() methods

  • int compareTo(String anotherString) - Compares two strings lexicographically. 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.
  • int compareToIgnoreCase(String str) - Compares two strings lexicographically, ignoring differences in case. 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.

In lexicographical comparison 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 character is different at some position then, compareTo returns the difference of the two character values, As Example if you are comparing run with sun then first char itself is different and difference between them is 1 so in that case -1 is retruned.

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings.

Example code

public class StringComparison {

    public static void main(String[] args) {
        String str1 = "run";
        String str2 = new String("run");
        String str3 = "gun";
        String str4 = "sun";
        
        //equal so returns 0
        System.out.println(str1.compareTo(str2));
        
        //str1 > str3 so returns positive integer
        System.out.println(str1.compareTo(str3));
        // that's how used generally
        if(str1.compareTo(str3) > 0){
            System.out.println("str1 is greater than str3");
        }else{
            System.out.println("str1 is less than str3");
        }
        
        // str1 < str4 so returns negative integer
        System.out.println(str1.compareTo(str4));       
    }
}

Output

0
11
str1 is greater than str3
-1

regionMatches() method

  • boolean regionMatches(int toffset, String other, int ooffset, int len) - Tests whether the specified region of this string matches the specified region of the String argument.
    Region is of length len and begins at the index toffset for this string and ooffset for the other string. This method is case sensitive.
  • boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) – Here first argument indicates whether case should be ignored; if true, case is ignored when comparing characters.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str1 = "This is an example string";
  String str2 = new String("example");
  String str3 = "Example";
  // returns true
  System.out.println(str1.regionMatches(11, str2, 0, str2.length()));
  // returns false
  System.out.println(str1.regionMatches(11, str3, 0, str3.length()));
  // returns true
  System.out.println(str1.regionMatches(true, 11, str3, 0, str3.length()));
 }

}

Output

true
false
true

Here in the first regionMatches() method the task is to compare “example” is the string str1 with the string str2. Since example starts at the index 11 so that becomes the offset for the first string. Comparison is to be done with the string str2 so that is the second argument. In str2 offset is 0. Here region to be comapred is the complete length of string str2 so str2.length() method is used.

In second case everything is same except the matched string str3 which has the content “Example”. Since method is case sensitive so returns false.

In third case first argument is passed as true so the case is ignored while comparing. That is why true is returned even when str1 and str3 are compared.

Matches() method for string comparison

  • public boolean matches(String regex) - Tells whether or not this string matches the given regular expression.

Example code

Let's say there is a String array with some strings and you want to match and print only those strings which doesn't contain any digit or special character. Then using matches method and providing a regular expression [a-z]+ which will match one or more chars it can be done as follows

.
public class StringComparison {

 public static void main(String[] args) {
  String[] words = {"a123","*67t","test","54&ty"};
  for(String str : words)
  {
      if(str.matches("[a-z]+"))
      {
          System.out.println("matched string - " + str);
      }
  }
 }
}

Ouput

matched string - test

That's all for this topic String comparison in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. How to reverse a string in Java
  3. How to add double quotes to a String
  4. String and thread-safety in Java
  5. Java String interview questions

You may also like -

>>>Go to Java Basics page

2 comments:


  1. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.


    Online Reputation Management

    ReplyDelete
  2. the blog is very interesting and will be much useful for us. thank you for sharing the blog with us. please keep on updating.
    Email Marketing Chennai

    ReplyDelete