w3resource

Scala Programming: Check whether a given string ends with the contents of another string

Scala Programming String Exercise-7 with Solution

Write a Scala program to check whether a given string ends with the contents of another string.

Sample Solution:

Scala Code:

object Scala_String {  
  def test(str1: String, end_str: String): Boolean = {
    str1.endsWith(end_str)   
  }
  def main(args: Array[String]): Unit = {
        val str1 ="Python Exercises";
        val str2 ="Python Exercise";

        // The String to check the above two Strings to see
        // if they end with this value (se).
        val end_str ="se";

        // Check first two Strings end with end_str
        val ends1 = test(str1, end_str)
        val ends2 = test(str2, end_str)
        // Display the results of the endsWith calls.
        println("\"" + str1 + "\" ends with " +
            "\"" + end_str + "\"? " + ends1);
        println("\"" + str2 + "\" ends with " +
            "\"" + end_str + "\"? " + ends2);
      }
}

Sample Output:

"Python Exercises" ends with "se"? false
"Python Exercise" ends with "se"? true

Scala Code Editor :

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

Previous: Write a Scala program to create a new String object with the contents of a character array.
Next: Write a Scala program to check whether two String objects contain the same data.

What is the difficulty level of this exercise?