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: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back

Scala Programming Basic Exercise-12 with Solution

Write a Scala program to create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back. If the given string length is less than 3, use whatever characters are there.

Sample Solution:

Scala Code:

object scala_basic {
  def test(str1: String): String =
    {
    if (str1.length < 3) str1 * 3
    else str1.substring(0, 3) + str1 + str1.substring(0, 3)
    }
   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: ScaScalaSca
Result: abcabcdabc
Result: ababab
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 check whether a given positive number is a multiple of 3 or a multiple of 7.
Next: Write a Scala program to check whether a given string starts with 'Sc' or not.

What is the difficulty level of this exercise?