Scala Programming: Add a string with specific number of times separated by a substring
Scala Programming String Exercise-34 with Solution
Write a Scala program to add a string with specific number of times separated by a substring.
Sample Solution:
Scala Code:
object Scala_String {
def test(main_str: String, sep_str: String, ctr: Int): String = {
var new_word = "";
for (i <- 0 to ctr - 1) {
if (i < ctr - 1)
new_word = new_word + (main_str + sep_str)
else
new_word += main_str;
}
return new_word;
}
def main(args: Array[String]): Unit = {
val str1 = "try";
val str2 = "best";
var ctr = 3;
println("The given strings are: " + str1 + " and " + str2);
println("Number to times to be repeat: " + ctr);
println("The new string is: " + test(str1, str2, ctr));
}
}
Sample Output:
The given strings are: try and best Number to times to be repeat: 3 The new string is: trybesttrybesttry
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to count how many times the substring 'life' present at anywhere in a given string. Counting can also happen for the substring 'li?e',any character instead of 'f'.
Next: Write a Scala program to repeat a specific number of characters for specific number of times from the last part of a given string.
What is the difficulty level of this exercise?
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-34.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics