w3resource

Scala Programming: A new string made of p number of characters from the first of a given string and followed by p-1 number characters till the p is greater than zero

Scala Programming String Exercise-41 with Solution

Write a Scala program to make a new string made of p number of characters from the first of a given string and followed by p-1 number characters till the p is greater than zero.

Sample Solution:

Scala Code:

object Scala_String {
  def test(stng: String, n: Int): String = {
  var l = n
  var newstring = "";
    
  for (i<-n to 0 by -1)
  {
    newstring = newstring + stng.substring(0,l);
    l = l -1;
  }
  return newstring;
  }

  def main(args: Array[String]): Unit = {
     val str1 =  "welcome";
	   val rep_no=4;
     println("The given string is: "+str1);
	   println("Number of repetition characters and repetition: "+rep_no);
     println("The new string is: "+ test(str1, rep_no));
  }
}

Sample Output:

The given string is: welcome
Number of repetition characters and repetition: 4
The new string is: welcwelwew

Scala Code Editor :

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

Previous: Write a Scala program to make a new string from two given string in such a way that, each character of two string will come respectively.
Next: Write a Scala program to make a new string with each character of just before and after of a non-empty substring whichever it appears in a non-empty given string.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/string/scala-string-exercise-41.php