w3resource

Scala Programming: Read a string and return true if it ends with a specified string of length 2

Scala Programming String Exercise-21 with Solution

Write a Scala program to read a string and return true if it ends with a specified string of length 2.

Sample Solution:

Scala Code:

object Scala_String {
  def test(str1: String, end_str: String): Boolean = {
    val len = str1.length
    val ng = end_str
    if (len < 2)
      false
    else if (ng.equals(str1.substring(len - 2, len)))
      true;
    else
      false
  }
  def main(args: Array[String]): Unit = {
    var str1 = "String";
    var end_str = "ng"
    println("The given strings is: " + str1)
    println("The string containing " + end_str + " at last: " + test(str1, end_str))
    end_str = "gn"
    println("The given strings is: " + str1)
    println("The string containing " + end_str + " at last: " + test(str1, end_str))
  }
}

Sample Output:

The given strings is: String
The string containing ng at last: true
The given strings is: String
The string containing gn at last: false

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 from a given string swapping the last two characters of the given string. The length of the given string must be two or more.
Next: Write a Scala program to read two strings append them together and return the result. If the length of the strings is different remove characters from the beginning of longer string and make them equal length.

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-21.php