w3resource

Scala Programming: Create a new string with the last char added at the front and back of a given string of length 1 or more

Scala Programming Basic Exercise-10 with Solution

Write a Scala program to create a new string with the last char added at the front and back of a given string of length 1 or more.

Sample Solution:

Scala Code:

object scala_basic {
  def test(str1: String): String = 
    {
    val len = str1.length
    val last = str1.charAt(len - 1)
    last + str1 + last
    }
     
   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: aScalaa
Result: dabcdd
Result: babb
Result: aaa

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 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.
Next: Write a Scala program to check whether a given positive number is a multiple of 3 or a multiple of 7.

What is the difficulty level of this exercise?