How to check whether subregions of two Strings are matching using the regionMatches() method
Coding River
How to check whether subregions of two Strings are matching using the regionMatches() method
In this video, we will talk about the Java regionMatches() method, which is used to test if two String regions are equal. What happens is that a substring of a given String object is compared to a substring of the String argument. This method returns a boolean value. It will return true if these String subregions are the same and matching, and by default this metod is case sensitive but it will ignore the case sensitivity of the String values if and only if ignoreCase is set to true.
In this first example I will show you how the first variation of this method works by default
String str1 = “I love programming”; String str2 = “Do you love it ?”; String str3 = “DO YOU LOVE IT?”;
Now let me apply the regionMatches() method to see if these two Strings match System.out.println(str1.regionMatches(5 , str2 , 0 , 4));
Let’s note here that:
5 : represents the starting index position of the subregion in the String variable str1. It is useful to determine the subregion of the String to be matched str2 : is the String argument and it represents the String with which we would like to have a match 0 : represents the starting index position of the subregion to be matched in the String argument str2 4 : is the number of characters to compare
If we run the program now, it will return "false", because the starting index positions defining the subregions to be matched are not matching
So, for this to return true, I will try to check whether the substring "love" in str1 matches the one in str2 by writing this statement System.out.println(str1.regionMatches(2 , str2 , 7 , 4)); Now, the program returns "true"
System.out.println(str1.regionMatches(2 , str3 , 7 , 4)); If we run this program, we will get in the console the value : false because this method is case sensitive
In the second example, I will show you how to make that the method would ignore the case sensitivity of the String values. All we have to do is to add another parameter like this
#codingriver #Java #Programming
System.out.println(str1.regionMatches(true, 2 , str3 , 7 , 4));
true : indicates that we want the method to ignore the case sensitivity Now, if we run our program, we will get "true" in our console ... https://www.youtube.com/watch?v=ozkr3d8nC-0
15025484 Bytes