Java String regionMatches() Method Example

1. Introduction

The String.regionMatches() method in Java is used to compare a region of one string with a region of another string. This method can be case-sensitive or case-insensitive, depending on which version of the method is called. It's useful for checking parts of strings without extracting them into new substrings. This tutorial will explain how to use both versions of the regionMatches() method.

Key Points

- regionMatches() checks if two string regions are equal.

- It allows specifying where the region starts in both the source string and the target string and how many characters to compare.

- There are two versions: one for case-sensitive and another for case-insensitive comparison.

2. Program Steps

1. Declare two strings to compare.

2. Specify indices and length for the comparison.

3. Perform a case-sensitive region comparison.

4. Perform a case-insensitive region comparison.

5. Print the results of both comparisons.

3. Code Program

public class StringRegionMatchesExample {
    public static void main(String[] args) {
        // Strings to compare
        String str1 = "Hello, Java!";
        String str2 = "I said hello, Java!";
        // Region comparison starting at index 7 for str1 and 9 for str2, comparing 5 characters
        boolean resultCaseSensitive = str1.regionMatches(7, str2, 9, 5);
        // Case-insensitive region comparison
        boolean resultCaseInsensitive = str1.regionMatches(true, 7, str2, 9, 5);
        // Printing results
        System.out.println("Case-sensitive match: " + resultCaseSensitive);
        System.out.println("Case-insensitive match: " + resultCaseInsensitive);
    }
}

Output:

Case-sensitive match: false
Case-insensitive match: true

Explanation:

1. String str1 = "Hello, Java!" and String str2 = "I said hello, Java!": Two strings are declared.

2. The method str1.regionMatches(7, str2, 9, 5) checks if the region starting at index 7 in str1 matches the region starting at index 9 in str2 for 5 characters, case-sensitive.

3. str1.regionMatches(true, 7, str2, 9, 5): Performs a case-insensitive region match for the same indices and length.

4. System.out.println("Case-sensitive match: " + resultCaseSensitive): Prints the result of the case-sensitive comparison.

5. System.out.println("Case-insensitive match: " + resultCaseInsensitive): Prints the result of the case-insensitive comparison.


Comments