Home » Scala programs » Scala string programs

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

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"

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'





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.