How to Match Regions in Strings Using Java



Matching regions in strings is a technique that allows us to check whether two different strings are the same over a specified range and are different outside that range. This is helpful in Java when comparison is only between parts of the string as opposed to the whole string.

Matching regions in string

The regionMatches() method compares a region from one string to a region in another string, starting at specified indices and comparing a certain number of characters. It returns true if the regions match and false otherwise

Syntax

The following is the syntax for Java String regionMatches() method

public boolean regionMatches(int toffset, String other, int ooffset, int len) // first syntax
or,
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) // second syntax

Java program to match regions in string

The following example to match regions in strings using Java.

public class StringRegionMatch {
   public static void main(String[] args) {
      String first_str = "Welcome to Microsoft";
      String second_str = "I work with Microsoft";
      boolean match = first_str.regionMatches(11, second_str, 12, 9);
      System.out.println("first_str[11 -19] == " + "second_str[12 - 21]:-"+ match);
   }
}

Output

first_str[11 -19] == second_str[12 - 21]:-true 

Code Explanation

11 is the index number in the source string from where comparison starts. Second_str is the destination string. 12 is the index number from where comparison should start in the destination string. 9 is the number of characters to compare.

java_strings.htm
Advertisements