What is the string regionMatches() method in Java?
The regionMatches() method in Java is used to check if two string regions are equal.
Syntax
The regionMatches() method can be declared as shown below:
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Parameters
-
ignoreCase: Ignores case when comparing if this argument istrue. It is an optional argument. -
toffset: The starting offset of the sub-region in this string. -
other: The string argument. -
ooffset: The starting offset of the sub-region in the string argument. -
len: The number of characters to compare.
Return value
The regionMatches() method returns true if the sub-region of this string matches the sub-region of the string argument. Otherwise, the regionMatches() method returns false.
Code
Consider the code snippet below, which demonstrates the use of the regionMatches() method.
import java.io.*;public class Main {public static void main(String args[]) {String str1 = new String("This is regionMatches() example");String str2 = new String("region");String str3 = new String("world");System.out.println("str1 and str2 region matches: " + str1.regionMatches(8, str2, 0, 6));System.out.println("str1 and str3 region matches: " + str1.regionMatches(8, str3, 0, 6));}}
Explanation
- Three strings,
str1,str2, andstr3, are declared in lines 5-7. - The
regionMatches()method is used in line 9 to check if the regions ofstr1andstr2match. - The
regionMatches()method is used in line 11 to check if the regions ofstr1andstr3match.