Scala Programming: Create a new string which is 4 copies of the 2 front characters of a given string
Scala Programming Basic Exercise-9 with Solution
Write a Scala program to create a new string which is 4 copies of the 2 front characters of a given string.If the given string length is less than 2 return the original string.
Sample Solution:
Scala Code:
object scala_basic {
def test(str1: String): String =
{
if (str1.length < 2) str1
else str1.substring(0, 2) * 4
}
def main(args: Array[String]): Unit = {
println("Result: " + test("Scala"));
println("Result: " + test("abcd"));
println("Result: " + test("ab"));
println("Result: " + test("a"));
}
}
Sample Output:
Result: ScScScSc Result: abababab Result: abababab Result: a
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to exchange the first and last characters in a given string and return the new string.
Next: Write a Scala program to create a new string with the last char added at the front and back of a given string of length 1 or more.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework