w3resource

Scala Programming: Check whether the first two characters present at the end of a given string

Scala Programming String Exercise-24 with Solution

Write a Scala program to check whether the first two characters present at the end of a given string.

Sample Solution:

Scala Code:

object Scala_String {

  def test(str1: String): Boolean = {
   if (str1.length < 2)
    return false;
  else if (str1.substring(0,2).equals(str1.substring(str1.length-2, str1.length)))
    return true;
  else
    return false;
  }

  def main(args: Array[String]): Unit = {
      var str1 =  "educated";	  
      println("The given strings is: "+str1);
      println("If first two characters appear in the last! "+test(str1));
      str1 =  "ABCDEFBA";	  
      println("The given strings is: "+str1);
      println("If first two characters appear in the last! "+test(str1));
  }
}

Sample Output:

The given strings is: educated
If first two characters appear in the last! true
The given strings is: ABCDEFBA
If first two characters appear in the last! false

Scala Code Editor :

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

Previous: Write a Java program to create a new string taking specified number of characters from first and last position of a given string.
Next: Write a Scala program to read a given string and if the first or last characters are same return the string without those characters otherwise return the string unchanged.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.