How to compare two strings in Scala? String compareTo() Method

Here, we are going to learn how to compare two strings in Scala using compareTo() method?
Submitted by Shivang Yadav, on January 29, 2021

String is an immutable collection that stores sequences of characters.

How to compare two strings in Scala?

In Scala, we can compare two strings and return the integer value denoting their difference using compareTo() method.

String compareTo() Method

The compareTo() method in Scala is used to compare two strings in Scala and return 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.compareTo(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

object MyClass {
    def main(args: Array[String]) {
        val string1 = "Scala"
        val string2 = "Scala"
        
        println("String1 = " + string1)
        println("String2 = " + string2)
        
        val compStr = string1.compareTo(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

Example 2: When both strings are not same

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

Output:

String1 = Scala
String2 = programming
Value of comparison between 'Scala' and 'programming' is -29

Example 3: When both strings are not the same

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

Output:

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


Comments and Discussions!

Load comments ↻





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