w3resource

Scala Programming: New string from two given string in such a way that, each character of two string will come respectively

Scala Programming String Exercise-40 with Solution

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.

Sample Solution:

Scala Code:

object Scala_String {
  def test(stng1: String, stng2: String): String = {
    val len1 = stng1.length;
    val len2 = stng2.length;
    var max_len = Math.max(len1, len2);
    var newstring = "";
    for (i <- 0 to max_len - 1) {
      if (i <= len1 - 1)
        newstring = newstring + stng1.substring(i, i + 1);
      if (i <= len2 - 1)
        newstring = newstring + stng2.substring(i, i + 1);
    }
    newstring;
  }

  def main(args: Array[String]): Unit = {
    val str1 = "welcome";
    val str2 = "w3resource";
    println("The given strings  are: " + str1 + "  and  " + str2);
    println("The new string is: " + test(str1, str2));
  }
}

Sample Output:

The given strings  are: welcome  and  w3resource
The new string is: wwe3lrceosmoeurce

Scala Code Editor :

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

Previous: Write a Scala program to create a new string repeating every character twice of a given string.
Next: 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.

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://w3resource.com/scala-exercises/string/scala-string-exercise-40.php