w3resource

Scala Programming: Create a new string which is n copies of a given string

Scala Programming Basic Exercise-26 with Solution

Write a Scala program to create a new string which is n (non-negative integer ) copies of a given string.

Sample Solution:

Scala Code:

object scala_basic {
   def test(str1: String, n: Int): String = {
    str1 * n;
  }

   def main(args: Array[String]): Unit = {
      println("Result: " + test("Scala", 2));
      println("Result: " + test("Python",1));
      println("Result: " + test("JS",6));      
    }
  }

Sample Output:

Result: ScalaScala
Result: Python
Result: JSJSJSJSJSJS

Scala Code Editor :

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

Previous: Write a Scala program to convert the last 4 characters of a given string in upper case. If the length of the string has less than 4 then uppercase all the characters.

What is the difficulty level of this exercise?