Scala Programming: Create a new string where 'if' is added to the front of a given string and if the string begins with "if" return the original
Scala Programming Basic Exercise-6 with Solution
Write a Scala program to create a new string where 'if' is added to the front of a given string. If the string already begins with 'if', return the string unchanged.
Sample Solution:
Scala Code:
// Define an object named scala_basic
object scala_basic {
// Define a function named test with a parameter str of type String, returning a String
def test(str: String): String =
{
// Check if the given string starts with "if"; if true, return the string as is, otherwise, prepend "if "
if (str.startsWith("if")) str else "if " + str
}
// Define the main method, which is the entry point of the program
def main(args: Array[String]): Unit = {
// Print the result of calling test with the argument "if else"
println("Result: " + test("if else"))
// Print the result of calling test with the argument "else"
println("Result: " + test("else"))
}
}
Sample Output:
Result: if else Result: if else
Explanation:
Here is the break down of the said Scala code:
- object scala_basic {: This declares an object named scala_basic.
- def test(str: String): String =: This line defines a function named test that takes a parameter str of type String and returns a String. The function checks if the given string starts with "if". If true, it returns the string as is; otherwise, it prepends "if " to the string.
- if (str.startsWith("if")) str else "if " + str: This is a conditional expression inside the test function. It checks if the given string str starts with "if". If true, it returns the string as is; if false, it concatenates "if " with the string and returns the result.
- def main(args: Array[String]): Unit = {: This line defines the main method, which is the entry point of the program. It takes an array of strings (args) as its parameter and returns Unit (similar to void in other languages).
- println("Result: " + test("if else")): This line calls the "test()" function with the argument "if else", concatenates the result with the string "Result: ", and prints the entire string to the console.
- println("Result: " + test("else")): Similar to the previous line, this calls the test function with the argument "else" and prints the result.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Check a given integer and return true if it is within 20 of 100 or 300.
Next: Remove the character in a given position of a given string. The given position will be in the range 0...string length -1 inclusive.
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/basic/scala-basic-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics