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 which is 4 copies of the 2 front characters of a given string

Scala Programming Basic Exercise-9 with Solution

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.

Sample Solution:

Scala Code:

object scala_basic {
  def test(str1: String): String = 
    {
    if (str1.length < 2) str1 
    else str1.substring(0, 2) * 4
    }
     
   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: ScScScSc
Result: abababab
Result: abababab
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 exchange the first and last characters in a given string and return the new string.
Next: 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.

What is the difficulty level of this exercise?