String’s regionMatches is used to compare substring of one string to substring of another.Here region may be refer to substring of String, so we are comparing regions of one string with another.
Method Syntax:
There are two overloaded version of regionMatches:
ignoreCase: It is boolean field to indicate whether to ignore case or not. toffset : It is start index of sub String of String on which this method is being called. other: It is other String by which this String will compare. ooffset: It is start index of substring of other argument String len : Number of characters to compare
Lets understand with the example:
You have two Strings and you want to match String java in both str1 and str2.
1
2
3
4
5
6
// 1st
Stringstr1="Hello world from java2blog.com";
//2nd
Stringstr2="Core java programming tutorials";
str1.regionMatches(17, str2, 5, 4) will do it. This expression will return true.
How?
17 is starting index of String java in str1.
str2 is our 2nd String
5 is starting index for String java in str2
4 is number of characters in String java
String regionMatches example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
packageorg.arpit.java2blog;
publicclassStringRegionMatchesExample{
publicstaticvoidmain(String[]args){
// 1st
Stringstr1="Hello world from java2blog.com";
//2nd
Stringstr2="Core java programming tutorials";
// 3rd
Stringstr3="JAVA PROGRAMMING TUTORIALS";
System.out.println("Comparing 1st and 2nd (java in both String): "+str1.regionMatches(17,str2,5,4));
// Ignoring case
System.out.println("Comparing 2nd and 3nd (programming in both string): "+str2.regionMatches(true,10,str3,5,4));
}
}
When you run above program, you will get below output: