w3resource

Scala function: Reverse a Given String

Scala Function Exercise-4 with Solution

Write a Scala function to reverse a given string.

Sample Solution:

Scala Code:

object StringReverser {
  def reverseString(str: String): String = {
    str.reverse
  }

  def main(args: Array[String]): Unit = {
    val input = "Scala, Code!"
    val reversed = reverseString(input)
    println(s"The reversed string of $input is: $reversed")
  }
}

Sample Output:

The reversed string of Scala, Code! is: !edoC ,alacS

Scala Code Editor :

Previous: Calculate the sum of digits in a number.
Next: Check if a string is a palindrome.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.