Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Scala Programming: Exchange the first and last characters in a given string and return the new string

Scala Programming Basic Exercise-8 with Solution

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

Sample Solution:

Scala Code:

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

Scala Code Editor :

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

Previous: Write a Scala program to remove the character in a given position of a given string. The given position will be in the range 0...string length -1 inclusive.
Next: Write a Scala program to create a new string which is 4 copies of the 2 front characters of a given string.If the given string length is less than 2 return the original string.

What is the difficulty level of this exercise?