Java String regionMatches example

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:
 // Case sensitive
public boolean regionMatches(int toffset, String other, int ooffset, int len):

// It has extra option to ignore the case
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

Parameters: 

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.
// 1st
String str1= "Hello world from java2blog.com";
//2nd
String str2= "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 :

package org.arpit.java2blog;

public class StringRegionMatchesExample {

 public static void main(String[] args) {
  // 1st
  String str1= "Hello world from java2blog.com";
  //2nd
  String str2= "Core java programming tutorials";
  // 3rd
  String str3= "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:
Comparing 1st and 2nd (java in both String): true
Comparing 2nd and 3nd (programming in both string): true

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012