Q:

Write a Scala program to exchange the first and last characters in a given string and return the new string

0

Write a Scala program to exchange the first and last characters in a given string and return the new string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

object scala_basic {
  def test(str1: String): String = 
    {
    val len = str1.length
    if (len <= 1) str1
    else str1.charAt(len - 1) + str1.substring(1, len - 1) + str1.charAt(0)
    }   
   def main(args: Array[String]): Unit = {
      println("Result: " + test("Scala"));
      println("Result: " + test("abcd"));
      println("Result: " + test("ab"));
      println("Result: " + test("a"));
    }
}

Sample Output:

Result: acalS
Result: dbca
Result: ba
Result: a

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now