w3resource

Scala function: Reverse a Given String


Write a Scala function to reverse a given string.


Before you start!

To solve this problem, you should have a basic understanding of:

  • Scala strings and how they are represented.
  • String manipulation methods in Scala.
  • How to iterate over characters in a string.
  • The built-in reverse method in Scala.

Try before looking at the solution!

Think about different ways to reverse a string:

  • How can you access individual characters of a string?
  • Is there a built-in method that can directly reverse a string?
  • If you were to reverse a string manually, how would you do it?
  • How can you use recursion or iteration to achieve the same result?

Try implementing a simple function to reverse a string before checking the solution!


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.