How to Match Regions in Strings in Java?
The regionMatches() method has two variants which can be used to test if two string regions are matching or equal.
Case sensitive test method:
public boolean regionMatches(int toffset, String other, int ooffset, int len)
It has the option to consider or ignore the case method:
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
- ignoreCase : if true, ignore case when comparing characters.
- toffset : the starting offset of the subregion in this string.
- other : the string argument being compared.
- ooffset : the starting offset of the subregion in the string argument.
- len : the number of characters to compare.
It returns true if the specified subregion of this string matches the specified subregion of the string argument, false otherwise. If ignoreCase is given true then it returns true or false being case insensitive.
Example 1 :
Result of Comparing of String 1 and String 2: true Result of Comparing of String 1 and String 3: false Result of Comparing of String 2 and String 3: false
Result of comparing String 1 and String 2 : true Result of comparing String 1 and String 3 : false Result of comparing String 2 and String 3 : true
The method returns false if atleast one of these are true,
- toffset is negative.
- ooffset is negative.
- toffset+len is greater than the length of this String object.
- ooffset+len is greater than the length of the other argument.
- ignoreCase is false and there is some nonnegative integer k less than len such that:
this.charAt(toffset+k) != other.charAt(ooffset+k)
- ignoreCase is true and there is some nonnegative integer k less than len such that:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.