Scala program to reverse a string

Scala | Reverse a string: Here, we are going to learn how to reverse a string in the Scala programming language?
Submitted by Shivang Yadav, on April 20, 2020 [Last updated : March 10, 2023]

Scala – Reverse a string

Logically, reversing is swapping the values from index 1 with index n, index 2 with index n-1, and so on.

So, if the string is "IncludeHelp", then the reverse will be "pleHedulcnI".

Example

    Input:
    String: "IncludeHelp"

    Output:
    Reversed string: "pleHedulcnI"

Example 1: Scala code to reverse a string

object myObject {
    def reverseString(newString: String): String = {
        var revString = ""
        val n = newString.length()
        for(i <- 0 to n-1){
            revString = revString.concat(newString.charAt(n-i-1).toString)
        }
    return revString
    }
    def main(args: Array[String]) {
        var newString = "IncludeHelp"
        println("Reverse of '" + newString + "' is '" + reverseString(newString) + "'")
    }
}

Output

Reverse of 'IncludeHelp' is 'pleHedulcnI'

Another method will be to convert the string into a list and then reversing the list and the converting in back to the string.

Example 2: Scala code to reverse a string

object myObject {
    def main(args: Array[String]) {
        var newString = "IncludeHelp"
        var revString = newString.foldLeft(List[Char]()){(x,y)=>y::x}.mkString("")
        println("Reverse of '" + newString + "' is '" + revString + "'")
    }
}

Output

Reverse of 'IncludeHelp' is 'pleHedulcnI'

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.