Java String - regionMatches() Method
The Java regionMatches() method is used to test if two string regions are equal. A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len.
Syntax
public boolean regionMatches(int toffset, String other, int ooffset, int len) public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Parameters
ignoreCase |
If true, ignore case when comparing characters. |
toffset |
Specify the starting offset of the subregion in this string. |
other |
Specify the string argument. |
ooffset |
Specify the starting offset of the subregion in the string argument. |
len |
Specify the number of characters to compare. |
Return Value
Returns true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument.
Exception
NA.
Example:
In the example below, regionMatches() method is used to compare two string regions.
public class MyClass { public static void main(String[] args) { String str1 = "Hello World!."; String str2 = "Hello Java!."; //comparing first five letters of two string Boolean result = str1.regionMatches(0, str2, 0, 5); //printing the result System.out.println("Are the String Regions equal?: " + result); } }
The output of the above code will be:
Are the String Regions equal?: true
Example:
In this example, string regions are compared where ignoreCase argument is also used.
public class MyClass { public static void main(String[] args) { String str1 = "Hello World!."; String str2 = "HELLO Java!."; //comparing first five letters of two string Boolean result = str1.regionMatches(true, 0, str2, 0, 5); //printing the result System.out.println("Are the String Regions equal?: " + result); } }
The output of the above code will be:
Are the String Regions equal?: true
❮ Java String Methods