regionMatches() used to compare substrings of two strings
java.lang.String class comes with many methods to check two strings contain same characters in the same sequence. To do this, String class comes with equals(), equalsIgnoreCase(), compareTo() and compareToIgnoreCase() methods.
All the above comparisons are used to compare whole strings. But regionMatches() compares parts of two strings or substrings of two strings.
regionMatches() is overloaded 2 times. The signatures are given hereunder as defined in String class.
- public boolean regionMatches(int sourcePosition, String destination, int destinationPosition, int len): Compares two regions of two strings of source and destination and returns a boolean value. With source, the method is called and the destination string is passed as parameter. It does case-sensitive comparison.
- sourcePosition: Index number of the character in the source string from where comparison should begin.
- destination: It is the destination string.
- destinationPosition: Index number of the character in the destination string from where comparison should begin.
- len: Number of characters to compare in both strings.
It is case-sensitive comparison.
- public boolean regionMatches(boolean case, int sourcePosition, String destination, int destinationPosition, int len): It is the just exactly the same of previous but added boolean value as first argument. true boolean value indicates case-insensitive comparison.
Following example illustrates the usage of both the regionMatches() methods.
public class StringMethodDemo
public static void main(String args)
String str1 = "RaoRajaSir";
String str2 = "RaniRajaMadam";
String str3 = "ranirajamadam";
boolean b1 = str1.regionMatches(3, str2, 4, 4);
System.out.println("Raja exists in both strigns: " + b1);
System.out.println("\nCase-sensitive comparison. Raja and raja exists in both strigns: " + str1.regionMatches(3, str3, 4, 4));
System.out.println("\nCase-insensitive comparison. Raja and raja exists in both strigns: " + str1.regionMatches(true, 3, str3, 4, 4));
str1.regionMatches(3, str2, 4, 4);
First Parameter: 3 is the index number in the source string from where comparison starts
Second Parameter: str2 is the destination string
Third Parameter: 4 is the index number from where comparison should start in destination string
Fourth Parameter: 4 is the number of characters to compare
That is, Raja region of string str1 and str2 are compared. As they are same, the method returned true. Here, case-sensitive comparison is done.
str1.regionMatches(true, 3, str3, 4, 4);
true indicates case-insensitive comparison, but for all arguments are same that of previous statement.