w3resource

Scala Programming: New string taking specified number of characters from first and last position of a given string

Scala Programming String Exercise-23 with Solution

Write a Java program to create a new string taking specified number of characters from first and last position of a given string.

Sample Solution:

Scala Code:

object Scala_String {

  def test(str1: String, n: Int): String = {
    str1.substring(0, n) + str1.substring(str1.length - n, str1.length);
  }

  def main(args: Array[String]): Unit = {
    var str1 = "Welcome";
    var n1 = 3;
    println("The given strings is: " + str1);
    println("The given numbers is: " + n1);
    println("The new string is: " + test(str1, n1));

    str1 = "Scala Programming";
    n1 = 4;
    println("The given strings is: " + str1);
    println("The given numbers is: " + n1);
    println("The new string is: " + test(str1, n1));
  }
}

Sample Output:

The given strings is: Welcome
The given numbers is: 3
The new string is: Welome
The given strings is: Scala Programming
The given numbers is: 4
The new string is: Scalming

Scala Code Editor :

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

Previous: Write a Scala program to read two strings append them together and return the result. If the length of the strings is different remove characters from the beginning of longer string and make them equal length.
Next: Write a Scala program to check whether the first two characters present at the end of a given string.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.