Reverse A String - 5 Methods

Reverse A String - 5 Methods

  • Method 1 - String Builder / String Buffer
// Using String builder and String buffer

public class Method1 {
    public static void main(String[] args) {

        // pass the string to reverse
        StringBuilder sb = new StringBuilder("Amritanshu");
        StringBuffer sbf = new StringBuffer("Rawat");

        // printing
        System.out.println("String Builder: "+ sb.reverse().toString());
        System.out.println("String Buffer: " + sbf.reverse().toString());
    }
}
  • Method 2 - String Concatenation
// String Concatenation

public class Method2 {
public static void main(String[] args) {

// String to reverse
String name = "Amritanshu Dev Rawat";

// empty string to store reverse string
String rev = "";

// reverse loop logic and appending to rev
for(int i = name.length()-1;i>=0;i--) {
rev += name.charAt(i);
    }

// printing
System.out.println(rev);

    }
}
  • Method 3 - Character Array
// Char array

public class Method3 {
public static void main(String[] args) {

// String to reverse
String name = "Amritanshu";

// converting to char array
char[] charName = name.toCharArray();

// reverse loop logic and printing
for(int i = charName.length -1; i>=0;i--) {
System.out.print(name.charAt(i));
        }
    }
}
  • Method 4 - Stack
// Stack

import java.util.Stack;

public class Method4 {
public static void main(String[] args) {

    // string to reverse
    String name = "Amritanshu";

    // empty character stack
    Stack<Character> charStack = new Stack<Character>();

    // push every character to stack
    char[] ch = name.toCharArray();
    for (int i = 0; i < name.length(); i++) {
        charStack.push(ch[i]);
    }

    // pop element and store
    int k =0;
    while(!charStack.isEmpty()) {
        ch[k++] = charStack.pop();
    }

    // convert char to string and print
    System.out.println(String.copyValueOf(ch));

    }
}
  • Method 5 - Swap
// Two Pointer swap

public class Method5 {
public static void main(String[] args) {
    // String to reverse
    String name = "Amritanshu Dev Rawat";

    // converting to char array
    char[] c = name.toCharArray();

    // one pointer at begin
    int begin=0;

    // one at end
    int end=c.length-1;

    // one to store value and swap
    char temp;

    // looping and swapping
    while(end>begin){
        temp = c[begin];
        c[begin]=c[end];
        c[end] = temp;
        end--;
        begin++;
    }

    //printing
    System.out.println(String.valueOf(c));
    }
}