w3resource

Scala Programming: Append two strings, remove characters from the beginning of longer string if the lengths of the string are different

Scala Programming String Exercise-22 with Solution

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.

Sample Solution:

Scala Code:

object Scala_String {

  def test(str1: String, str2: String): String = {
    if (str1.length == str2.length)
      return str1 + str2;
    if (str1.length > str2.length) {
      var diff = str1.length - str2.length;
      str1.substring(diff, str1.length) + str2;
    } else {
      var diff = str2.length - str1.length;
      str1 + str2.substring(diff, str2.length);
    }
  }
  def main(args: Array[String]): Unit = {
    var str1 = "Welcome";
    var str2 = "home";
    println("The given strings is: " + str1 + " and " + str2);
    println("The new string is: " + test(str1, str2));
    str1 = "Scala";
    str2 = "Python";
    println("The given strings is: " + str1 + " and " + str2);
    println("The new string is: " + test(str1, str2));
  }
} 

Sample Output:

The given strings is: Welcome and home
The new string is: comehome
The given strings is: Scala and Python
The new string is: Scalaython

Scala Code Editor :

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

Previous: Write a Scala program to read a string and return true if it ends with a specified string of length 2.
Next: Write a Java program to create a new string taking specified number of characters from first and last position of a given string.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.