Scala String regionMatches() Method with Example

Here, we will learn about the regionMatches() method of String class in Scala. It is used to check if the region in the two strings are matched or not. We will see its working, syntax and example.
Submitted by Shivang Yadav, on February 03, 2021

String is an immutable collection that stores sequences of characters.

String regionMatches() Method

The regionMatches() method in Scala is used to check if the given region (substring) is common between the two strings or not. It checks both the string regions for equal and returns a Boolean value based on the comparison.

The case difference between the two methods can be ignored by using the ignoreCase parameter and stating it true, it is the parameter of the method.

Syntax:

string1_Name.regionMatches(
    boolean ignoreCase, 
    int toOffSet, 
    string String2_Name, 
    int offSet, 
    int length
    ) 

Parameters: The method accepts the following parameters,

  1. ignoreCase: A boolean value which is used to tell the compiler to ignore the case difference.
  2. toOffSet: It is an integer for offSet.
  3. string2_Name: The second string whose region is to be matched.
  4. offSet: The starting index of the region.
  5. Length: The length of the region.

Return Value: It returns a Boolean value which states whether the region matches or not.

Example 1:

object myObject {
    def main(args: Array[String]) {
        val string1 = "includehelp"
        val isMatchedStrings = string1.regionMatches(false, 0, "IncludeHelp", 0, string1.length())
        
        if(isMatchedStrings){
            println("The regions of both the strings are matched...")
        }
        else{
            println("The regions of both the strings are not matched...")
        }
    }
}

Output:

The regions of both the strings are not matched...

Example 2: Ignoring case difference in the method

object myObject {
    def main(args: Array[String]) {
        val string1 = "includehelp"
        val isMatchedStrings = string1.regionMatches(true, 0, "IncludeHelp", 0, string1.length())
        
        if(isMatchedStrings){
            println("The regions of both the strings are matched...")
        }
        else{
            println("The regions of both the strings are not matched...")
        }
    }
}

Output:

The regions of both the strings are matched...

In the second example, the second string which has case difference is matched to true because we have toggled ignoreCase parameter to true. Else it would have been false if cases were considered.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.