Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Reverse a String in Golang?
Next article icon

How to reverse a String in Scala?

Last Updated : 29 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = "GeeksforGeeks"
Output: skeeGrofskeeG

Input: S= "String"
Output: gnirtS

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 = "GeeksforGeeks"     val reversedStr = str.reverse     println(reversedStr)    } } 

Output:

Screenshot-2024-04-02-at-15-27-50-Scastie---An-interactive-playground-for-Scala

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 = "GeeksforGeeks"     var reversedStr = ""     for (i <- str.length - 1 to 0 by -1) {       reversedStr += str(i)     }     println(reversedStr)    } } 

Output:

Screenshot-2024-04-02-at-15-27-50-Scastie---An-interactive-playground-for-Scala

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 = "GeeksforGeeks"     def reverseString(s: String): String = {       if (s.isEmpty) ""       else reverseString(s.tail) + s.head     }     val reversedStr = reverseString(str)     println(reversedStr)    } } 

Output:

Screenshot-2024-04-02-at-15-27-50-Scastie---An-interactive-playground-for-Scala

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


Next Article
How to Reverse a String in Golang?

A

anjalibo6rb0
Improve
Article Tags :
  • Scala

Similar Reads

  • How to reverse a list in scala
    In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. We use reverse function to reverse a list in Scala. Below are the examples to reverse a list. Reverse a simple list // Scala program to reverse a simple Imm
    2 min read
  • How to Reverse a String in Golang?
    Given a string and the task is to reverse the string. Here are a few examples. Approach 1: Reverse the string by swapping the letters, like first with last and second with second last and so on. Example: [GFGTABS] C // Golang program to reverse a string package main // importing fmt import "fmt
    2 min read
  • How to Sort a list in Scala?
    Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S
    2 min read
  • Reverse a String in TypeScript
    Reversing a string involves changing the order of its characters, so the last character becomes the first, and vice versa. In TypeScript, there are various methods to achieve this, depending on the developer's preference and the specific requirements of the task. Table of Content Using a LoopUsing A
    2 min read
  • How to Reverse keys and values in Scala Map
    In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to reverse the keys and values in given Map in Scala. After reversing the pairs, keys will become values and values will become keys. We can reverse the keys and values of a map with a Scala for-compr
    2 min read
  • How to Sort an Array in Scala?
    Sorting arrays effectively is essential for many applications, regardless of whether you're working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situati
    5 min read
  • Scala Stack reverse() method with example
    In Scala Stack class, the reverse() method is utilized to return a stack with the reverse order. Method Definition: def reverse: Stack[A] Return Type: It returns a stack with the reverse order. Example #1: // Scala program of reverse() // method // Import Stack import scala.collection.mutable._ // C
    1 min read
  • How to remove duplicate characters from a String in Scala?
    In this article, we will learn how to remove duplicate characters from a string in Scala using different approaches. First, we will look through the Brute-Force Approach and then use different standard libraries. Examples: Input: String = "hello"Output: helo Input: String = "Geeks"Output: Geks Naive
    4 min read
  • Scala String replaceFirst() method with example
    The replaceFirst() method is same as replaceAll but here only the first appearance of the stated sub-string will be replaced. Method Definition: String replaceFirst(String regex, String replacement) Return Type: It returns the stated string after replacing the first appearance of stated regular expr
    1 min read
  • Program to print Java Set of Strings in Scala
    A java Set of strings can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences