×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String compareToIgnoreCase() Method with Example

By IncludeHelp Last updated : October 21, 2024

Description and Usage

The compareToIgnoreCase() method in Scala is used to compare two strings in Scala by ignoring case differences. It returns an integer value denoting the difference.

The value of comparison is determined as:

  • 0, if both strings are the same.
  • x, if string1 is greater than string2. The value of x is denoted by the difference of value of characters.
  • -x, if string1 is smaller than string2. The value of x is denoted by the difference of value of characters.

Syntax

string1.compareToIgnoreCase(string2)

Parameters

The method accepts a single parameter which is the string to be compared.

Return Value

It returns an integer value which denotes the result of difference between the strings.

Example 1: When both strings are the same but contain case difference

object MyClass {
    def main(args: Array[String]) {
        val string1 = "Scala"
        val string2 = "scala"
    
        println("String1 = " + string1)
        println("String2 = " + string2)
    
        val compStr = string1.compareToIgnoreCase(string2)
        println("Value of comparison between '" + string1 + "' and '" + string2 + "' is " + compStr)
    }
}

Output

String1 = Scala
String2 = scala
Value of comparison between 'Scala' and 'scala' is 0

Here, the result of comparison is zero denoting the string are equal even though they have case difference as we have used the compareToIgnoreCase() method.

Example 2: When both strings are not same

object MyClass {
    def main(args: Array[String]) {
        val string1 = "Scala"
        val string2 = "scalaProgramming"
    
        println("String1 = " + string1)
        println("String2 = " + string2)
    
        val compStr = string1.compareToIgnoreCase(string2)
        println("Value of comparison between '" + string1 + "' and '" + string2 + "' is " + compStr)
    }
}

Output

String1 = Scala
String2 = scalaProgramming
Value of comparison between 'Scala' and 'scalaProgramming' is -11

Example 3: When both strings are not the same

object MyClass {
    def main(args: Array[String]) {
        val string1 = "ScalaProgrammingLanguage"
        val string2 = "scalaProgramming"
    
        println("String1 = " + string1)
        println("String2 = " + string2)
    
        val compStr = string1.compareToIgnoreCase(string2)
        println("Value of comparison between '" + string1 + "' and '" + string2 + "' is " + compStr)
    }
}

Output

String1 = ScalaProgrammingLanguage
String2 = scalaProgramming
Value of comparison between 'ScalaProgrammingLanguage' and 'scalaProgramming' is 8

Comments and Discussions!

Load comments ↻





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