Reverse a String in Scala

Below are the possible approaches to reverse a string in Scala.

Approach 1: Using the reverse method

  1. In this approach, we are using the reverse method available for strings in Scala, which directly reverses the order of characters in the string.
  2. This method provides a simple and concise way to reverse a string without the need for manual iteration or recursion.
  3. By calling reverse on the string, we obtain the reversed version of the original string.

In the below example, the reverse method is used to reverse a string in Scala.

Scala
object GFG {
  def main(args: Array[String]): Unit = {
    val str = "w3wiki"
    val reversedStr = str.reverse
    println(reversedStr) 
  }
}

Output:

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach 2: Using a Loop

  1. In this approach, we initialize an empty string reversedStr and iterate over the characters of the input string str in reverse order using a for loop.
  2. Within each iteration, we append the character at index i to the reversedStr string, effectively reversing the original string.
  3. Finally, we print the reversed string using println(reversedStr).

In the below example, a Loop is used to reverse a string in Scala.

Scala
object GFG {
  def main(args: Array[String]): Unit = {
    val str = "w3wiki"
    var reversedStr = ""
    for (i <- str.length - 1 to 0 by -1) {
      reversedStr += str(i)
    }
    println(reversedStr) 
  }
}

Output:

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach 3: Using Recursion

  1. In this approach, we define a recursive function reverseString that takes a string s as input. The function checks if the string s is empty, in which case it returns an empty string.
  2. Otherwise, it recursively calls itself with the tail of the string s (i.e., all characters except the first one) and appends the first character of s to the result of the recursive call.
  3. This process effectively reverses the string. Finally, we call reverseString with the input string str and print the reversed string using println(reversedStr).

In the below example, recursion is used to reverse a string in Scala.

Scala
object GFG {
  def main(args: Array[String]): Unit = {
    val str = "w3wiki"
    def reverseString(s: String): String = {
      if (s.isEmpty) ""
      else reverseString(s.tail) + s.head
    }
    val reversedStr = reverseString(str)
    println(reversedStr) 
  }
}

Output:

Time Complexity: O(N)
Auxiliary Space: O(1)



How to reverse a String in Scala?

In this article, we will learn to reverse a string in Scala. Reverse of a string means changing its order so that the last character becomes the first, the second-to-last becomes the second, and so on, effectively flipping the string’s sequence of characters.

Examples:

Input: S = “w3wiki”
Output: skeeGrofskeeG

Input: S= “String”
Output: gnirtS

Similar Reads

Reverse a String in Scala

Below are the possible approaches to reverse a string in Scala....