w3resource

Scala Programming: Compare two strings lexicographically

Scala Programming String Exercise-3 with Solution

Write a Scala program to compare two strings lexicographically.

Note: Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions.

Sample Solution:

Scala Code:

object Scala_String {

  def test(str1: String, str2: String): String = {
    // Compare the two strings.
    val result = str1.compareTo(str2);

    // Display the results of the comparison.
    if (result < 0) {
      ("\"" + str1 + "\"" +
        " is less than " +
        "\"" + str2 + "\"");
    } else if (result == 0) {
      ("\"" + str1 + "\"" +
        " is equal to " +
        "\"" + str2 + "\"");
    } else {
      ("\"" + str1 + "\"" +
        " is greater than " +
        "\"" + str2 + "\"");
    }
  }

  def main(args: Array[String]): Unit = {
    var str1 = "This is Exercise 1";
    var str2 = "This is Exercise 2";

    println("String 1: " + str1);
    println("String 2: " + str2);

    var result = test(str1, str2)
    println(result)
    println("========================")
    str1 = "This is Exercise 1";
    str2 = "This is Exercise 1";

    println("String 1: " + str1);
    println("String 2: " + str2);

    result = test(str1, str2)
    println(result)
    println("========================")
    str1 = "This is Blacky";
    str2 = "This is Black";
    println("String 1: " + str1);
    println("String 2: " + str2);
    result = test(str1, str2)
    println(result)
  }
}

Sample Output:

ring 1: This is Exercise 1
String 2: This is Exercise 2
"This is Exercise 1" is less than "This is Exercise 2"
========================
String 1: This is Exercise 1
String 2: This is Exercise 1
"This is Exercise 1" is equal to "This is Exercise 1"
========================
String 1: This is Blacky
String 2: This is Black
"This is Blacky" is greater than "This is Black"

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to get the character (Unicode code point) at the given index within the String.
Next: Write a Scala program to concatenate a given string to the end of another string.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/string/scala-string-exercise-3.php