Q:

Scala program to reverse a string

0

Reversing 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"

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to reverse a string in Scala

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.

Program:

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'

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now