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:

// Define an object named scala_basic
object scala_basic {
  // Define a function named test with parameters str1 of type String and n of type Int, returning a String
  def test(str1: String, n: Int): String = {
    // Repeat the string str1 n times using the * operator
    str1 * n
  }

  // Define the main method, which is the entry point of the program
  def main(args: Array[String]): Unit = {
    // Print the result of calling test with the arguments "Scala" and 2
    println("Result: " + test("Scala", 2))

    // Print the result of calling test with the arguments "Python" and 1
    println("Result: " + test("Python", 1))

    // Print the result of calling test with the arguments "JS" and 6
    println("Result: " + test("JS", 6))
  }
}

Sample Output:

Result: ScalaScala
Result: Python
Result: JSJSJSJSJSJS

Explanation:

Here is the break down of the said Scala code:

  • object scala_basic {: This declares an object named scala_basic.
  • def test(str1: String, n: Int): String = {: This line defines a function named test that takes two parameters (str1 of type String and n of type Int) and returns a String.
  • str1 n: This line uses the operator to repeat the string str1 n times, creating a new string.
  • }: Closes the test function.
  • def main(args: Array[String]): Unit = {: This line defines the main method, which is the entry point of the program. It takes an array of strings (args) as its parameter and returns Unit (similar to void in other languages).
  • println("Result: " + test("Scala", 2)): This line calls the "test()" function with the arguments "Scala" and 2, and prints the result to the console.
  • println("Result: " + test("Python", 1)): Another call to the "test()" function with the arguments "Python" and 1.
  • println("Result: " + test("JS", 6)): Another call to the "test()" function with the arguments "JS" and 6.

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

Previous: 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?



Follow us on Facebook and Twitter for latest update.