How to Reverse a String

Posted by
How to Reverse a String in Java And Python

Last updated on October 14th, 2020

You can reverse a given string in many different ways in different programming languages. This guide tells you how to reverse a string in Python and Java in different ways. 

How to Reverse a String in Java?

To reverse a string in Java, you will need to make sure you understand the difference between String vs StringBuilder vs StringBuffer in Java

1. Using StringBuffer

Convert the input string to StringBuffer which is done by using the reverse method of StringBuffer. 

public class ReverseString
{
  public static void main(String[] args)
  {
    String str = "Hello World";
    // conversion from String object to StringBuffer 
    StringBuffer sbr = new StringBuffer(str); 
   // To reverse the string 
    sbr.reverse(); 
    System.out.println(sbr);  
  }
}

2. Built-in reverse() method of the StringBuilder class

The easiest way to reverse a string in java is by using the built-in reverse() method of the string builder class. String class does not have a reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. 

public class ReverseString
{
  public static void main(String[] args)
  {
    String str = "Hello World";
    StringBuilder s = new StringBuilder();
    s.append(str); //append a string into StringBuilder s
    s = s.reverse(); //reverse StringBuilder s 
    System.out.println(s); // print reversed String 
  }
}

3. Convert String to character array

Convert String to character array by using the built-in Java String class method toCharArray(). Scan the string from end to start and print the character one by one. 

public class ReverseString
{
  public static void main(String[] args)
  {
   String str = "Hello World";
   char[] s = str.toCharArray(); //Convert str to char Array
     for (int i = s.length - 1; i >= 0; i--)
         System.out.print(s[i]);
  } 
}

4. Scan the Character Array from Both Sides

Convert the input string into character array by using the toCharArray(). Then, scan the character array from both sides i.e from the start index (left) as well as from last index(right) simultaneously.

public class ReverseString
{
  public static void main(String[] args)
  {
   String str = "Hello World";
   char[] s = str.toCharArray(); //Convert str to char Array
   int left, right = 0; 
   right = s.length - 1; 
   for (left = 0; left < right; left++, right--) 
   { 
            // Swap values of left and right 
            char temp = s[left]; 
            s[left] = s[right]; 
            s[right] = temp; 
   } 

    for (char c : s) 
            System.out.print(c); 
    System.out.println(); 
   }
}

5. ArrayList Object

Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object, to reverse the list, we will pass the ArrayList object which is a type of list of characters.

import java.util.*;
public class ReverseString 
{ 
    public static void main(String[] args) 
    { 
        String str = "Hello World"; 
        char[] ch = str.toCharArray(); 
        List<Character> ch1 = new ArrayList<>(); 
  
        for (char c : ch) 
            ch1.add(c); 
  
        Collections.reverse(ch1); 
        ListIterator li = ch1.listIterator(); 
        while (li.hasNext()) 
            System.out.print(li.next()); 
    } 
} 

6. Convert String into Bytes

Create a temporary byte[] of length equal to the length of the input string. Store the bytes got from getBytes() method which is used to convert the input string into bytes[] in reverse order into temporary byte[]. Create a new string object using byte[] to store result.

public class ReverseString 
{ 
  public static void main(String[] args) 
  { 
   String str = "Hello World"; 
   byte[] sbt = str.getBytes(); 
   byte[] result = new byte[sbt.length]; 
   //Store result in reverse order into the result byte[]
   for (int i = 0; i < sbt.length; i++) 
           result[i] = sbt[sbt.length - i - 1]; 
   System.out.println(new String(result)); 
  } 
}

How to Reverse a String in Python?

There are three main ways to reverse a string in Python. 

1. Slice the String

Create a slice that start with the length of the string and ends at index 0. You can reverse a string using slicing with or without specifying the length of the string. 

str="Hello World" # initial string
stringlength=len(str) # calculate length of the list
slicedString=str[stringlength::-1] #slicing 
#slicedString = str[::-1] #WithoutStringLength
print (slicedString) #print the reversed string

2. Use the Loop

Create a new array and loop over the list with iterating variable, initialized with the length of the list. Each iteration, concatenate the value of the string. We then simply keep iterating until the index is less than zero.

str = "Hello World" # initial string
reversedString=[]
index = len(str) 
while index > 0: 
    reversedString += str[ index - 1 ] 
    index = index - 1 # decrement index
reversedString=''.join(reversed(str)) 
print(reversedString) #print the reversed string

3. Use Join with the built-in function

Reverses a string using reverse iteration with the reversed() built-in function to cycle through the elements in the string in reverse order and then use .join() method to merge all of the characters resulting from the reversed iteration into a new string.

str = 'Hello World' #initial string
reversed =''.join(reversed(str)) #merges all of the chars
print(reversed) #print the reversed string

4. Recursion

String is passed as an argument to a recursive function to reverse the string.

str = 'Hello World'
def reverse(str): 
    if len(str) == 0: 
        return str 
    else: 
        return reverse(str[1:]) + str[0]  
print(reverse(str))

5. Stack

Create an empty stack. Once the stack is created then one by one character of the string is pushed to the stack. One by one all characters from the stack are popped and put them back to a string.

#Create an Empty Stack
def createStack():
  stack = [] 
  return stack

def size(stack):
    return len(stack)

def isEmpty(stack): 
  if size(stack) == 0: 
    return true

def push(stack,item): 
    stack.append(item) 

def pop(stack): 
    if isEmpty(stack): return
    return stack.pop()  

# A stack based function to reverse a string 
def reverse(string): 
    n = len(string) 
       
    # Create a empty stack 
    stack = createStack() 
   
    # Push all characters of string to stack 
    for i in range(0,n,1): 
        push(stack,string[i]) 
   
    # Making the string empty since all 
    # characters are saved in stack     
    string="" 
   
    # Pop all characters of string and put 
    # them back to string 
    for i in range(0,n,1): 
        string+=pop(stack) 
           
    return string

#Print the reversed string 
str = "Hello World"
print (reverse(str))