Home » Java » Reverse a string in Java

Reverse a string in Java

Posted by: admin November 2, 2017 Leave a comment

Questions:

I have "Hello World" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there is some kind of a function already built-in into Java that does that.

Related: Reverse each individual word of “Hello World” string with Java

Answers:

You can use this:

new StringBuilder(hi).reverse().toString()

Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API. Thanks commentators for pointing out that StringBuilder is preferred nowadays.

Questions:
Answers:

For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:

public static String reverse(String input){
    char[] in = input.toCharArray();
    int begin=0;
    int end=in.length-1;
    char temp;
    while(end>begin){
        temp = in[begin];
        in[begin]=in[end];
        in[end] = temp;
        end--;
        begin++;
    }
    return new String(in);
}

Questions:
Answers:
public static String reverseIt(String source) {
    int i, len = source.length();
    StringBuilder dest = new StringBuilder(len);

    for (i = (len - 1); i >= 0; i--){
        dest.append(source.charAt(i));
    }

    return dest.toString();
}

http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm

Questions:
Answers:
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);

Questions:
Answers:

I am doing this using following two ways:

Reverse string by CHARACTERS:

public static void main(String[] args) {
    // Using treditonal approach
    String result="";
    for (int i=string.length()-1; i>=0; i--) {
        result = result + string.charAt(i);
    }
    System.out.println(result);

    // Using StringBuffer class
    StringBuffer buffer = new StringBuffer(string);
    System.out.println(buffer.reverse());    
}

Reverse string by WORDS:

public static void reverseStringByWords(String string) {
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = string.split(" ");

    for (int j = words.length-1; j >= 0; j--) {
        stringBuilder.append(words[j]).append(' ');
    }
    System.out.println("Reverse words: " + stringBuilder);
}

Questions:
Answers:

Here is an example using recursion:

public void reverseString() {
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}

String reverse(String stringToReverse, int index){
    if(index == 0){
        return stringToReverse.charAt(0) + "";
    }

    char letter = stringToReverse.charAt(index);
    return letter + reverse(stringToReverse, index-1);
}

Questions:
Answers:

Take a look at the Java 6 API under StringBuffer

String s = "sample";
String result = new StringBuffer(s).reverse().toString();

Questions:
Answers:

Here is a low level solution:

import java.util.Scanner;

public class class1 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String inpStr = in.nextLine();
        System.out.println("Original String :" + inpStr);
        char temp;
        char[] arr = inpStr.toCharArray();
        int len = arr.length;
        for(int i=0; i<(inpStr.length())/2; i++,len--){
            temp = arr[i];
            arr[i] = arr[len-1];
            arr[len-1] = temp;
        }

        System.out.println("Reverse String :" + String.valueOf(arr));
    }
}

Questions:
Answers:

I tried, just for fun, by using a Stack. Here my code:

public String reverseString(String s) {
    Stack<Character> stack = new Stack<Character>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        stack.push(s.charAt(i));
    }
    while (!stack.empty()) {
        sb.append(stack.pop());
    }
    return sb.toString();

}

Questions:
Answers:

Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.

The Algorithm is based on :

1.(A XOR B) XOR B = A

2.(A XOR B) XOR A = B

Code snippet:

public class ReverseUsingXOR {
    public static void main(String[] args) {
        String str = "prateek";
        reverseUsingXOR(str.toCharArray());
    }   

    /*Example:
     * str= prateek;
     * str[low]=p;
     * str[high]=k;
     * str[low]=p^k;
     * str[high]=(p^k)^k =p;
     * str[low]=(p^k)^p=k;
     * 
     * */
    public static void reverseUsingXOR(char[] str) {
        int low = 0;
        int high = str.length - 1;

        while (low < high) {
            str[low] = (char) (str[low] ^ str[high]);
            str[high] = (char) (str[low] ^ str[high]);   
            str[low] = (char) (str[low] ^ str[high]);
            low++;
            high--;
        }

        //display reversed string
        for (int i = 0; i < str.length; i++) {
            System.out.print(str[i]);
        }
    }

}

Output:

keetarp

Questions:
Answers:

It is very simple in minimum code of lines

public class ReverseString {
    public static void main(String[] args) {
        String s1 = "neelendra";
        for(int i=s1.length()-1;i>=0;i--)
            {
                System.out.print(s1.charAt(i));
            }
    }
}

Questions:
Answers:

As others have pointed out the preferred way is to use:

new StringBuilder(hi).reverse().toString()

but if you want to implement this by youself, i’am afraid that the rest of responses have flaws.

The reason is that String represent a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.

This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive “high” and “low” surrogates)

public static String reverseString(String s) {
    char[] chars = new char[s.length()];
    boolean twoCharCodepoint = false;
    for (int i = 0; i < s.length(); i++) {
        chars[s.length() - 1 - i] = s.charAt(i);
        if (twoCharCodepoint) {
            swap(chars, s.length() - 1 - i, s.length() - i);
        }
        twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
    }
    return new String(chars);
}

private static void swap(char[] array, int i, int j) {
    char temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
    StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
    sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
    sb.append(".");
    fos.write(sb.toString().getBytes("UTF-16"));
    fos.write("\n".getBytes("UTF-16"));
    fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}

Questions:
Answers:

This did the trick for me

public static void main(String[] args) {

    String text = "abcdefghijklmnopqrstuvwxyz";

    for (int i = (text.length() - 1); i >= 0; i--) {
        System.out.print(text.charAt(i));
    }
}

Questions:
Answers:
System.out.print("Please enter your name: ");
String name = keyboard.nextLine();

String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);

I used this method to turn names backwards and into lower case.

Questions:
Answers:
    public String reverse(String s) {

        String reversedString = "";
        for(int i=s.length(); i>0; i--) {
            reversedString += s.charAt(i-1);
        }   

        return reversedString;
    }

Questions:
Answers:

One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.

String s = "Hello My name is Sufiyan";

Put it in the stack frontwards

Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
     myStack.push(st.nextToken());
}

Print the stack backwards

System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
  System.out.print(myStack.pop());
  System.out.print(' ');
}

System.out.println('"');

Questions:
Answers:
public class Test {

public static void main(String args[]) {
   StringBuffer buffer = new StringBuffer("Game Plan");
   buffer.reverse();
   System.out.println(buffer);
 }  
}

Questions:
Answers:

All above solution is too good but here I am making reverse string using recursive programming.

This is helpful for who is looking recursive way of doing reverse string.

public class ReversString {

public static void main(String args[]) {
    char s[] = "Dhiral Pandya".toCharArray();
    String r = new String(reverse(0, s));
    System.out.println(r);
}

public static char[] reverse(int i, char source[]) {

    if (source.length / 2 == i) {
        return source;
    }

    char t = source[i];
    source[i] = source[source.length - 1 - i];
    source[source.length - 1 - i] = t;

    i++;
    return reverse(i, source);

}

}

Questions:
Answers:
public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 try{

  String str=br.readLine();
  char[] charArray=str.toCharArray();
  for(int i=charArray.length-1; i>=0; i--){
   System.out.println(charArray[i]);
  }
  }
   catch(IOException ex){
  }

Questions:
Answers:
import java.util.Scanner;
public class StringReverseExample
{
    public static void main(String[] args)
    {
        String str,rev;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string : ");
        str = in.nextLine();
        rev = new StringBuffer(str).reverse().toString();
        System.out.println("\nString before reverse:"+str);
        System.out.println("String after reverse:"+rev);
    }
}
/* Output : 
Enter the string : satyam

String before reverse:satyam
String after reverse:maytas */

Questions:
Answers:
package logicprogram;
import java.io.*;

public class Strinrevers {
public static void main(String args[])throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("enter data");
    String data=br.readLine();
    System.out.println(data);
    String str="";
    char cha[]=data.toCharArray();

    int l=data.length();
    int k=l-1;
    System.out.println(l);


    for(int i=0;k>=i;k--)
    {

        str+=cha[k];


    }
    //String text=String.valueOf(ch);
    System.out.println(str);

}

}

Questions:
Answers:
import java.util.Scanner;

public class Test {

    public static void main(String[] args){
        Scanner input = new Scanner (System.in);
        String word = input.next();
        String reverse = "";
        for(int i=word.length()-1; i>=0; i--)
            reverse += word.charAt(i);
        System.out.println(reverse);        
    }
}

If you want to use a simple for loop!

Questions:
Answers:

It gets the value you typed and returns it reversed 😉

public static  String reverse (String a){
    char[] rarray = a.toCharArray();
    String finalvalue = "";
    for (int i = 0; i < rarray.length; i++)
    {
        finalvalue += rarray[rarray.length - 1 - i];
    }   
return finalvalue;

}

Questions:
Answers:

public String reverseWords(String s) {

    String reversedWords = "";

    if(s.length()<=0) {
        return reversedWords;
    }else if(s.length() == 1){
        if(s == " "){
            return "";
        }
        return s;
    }

    char arr[] = s.toCharArray();
    int j = arr.length-1;
    while(j >= 0 ){
        if( arr[j] == ' '){
            reversedWords+=arr[j];
        }else{
            String temp="";
            while(j>=0 && arr[j] != ' '){
                temp+=arr[j];
                j--;
            }
            j++;
            temp = reverseWord(temp);
            reversedWords+=temp;
        }
        j--;

    }

    String[] chk = reversedWords.split(" ");

    if(chk == null || chk.length == 0){
        return "";
    }

    return reversedWords;



}

public String reverseWord(String s){

    char[] arr = s.toCharArray();

    for(int i=0,j=arr.length-1;i<=j;i++,j--){
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    return String.valueOf(arr);

}

Questions:
Answers:
StringBuilder s = new StringBuilder("racecar");
    for (int i = 0, j = s.length() - 1; i < (s.length()/2); i++, j--) {
        char temp = s.charAt(i);
        s.setCharAt(i, s.charAt(j));
        s.setCharAt(j, temp);
    }

    System.out.println(s.toString());

Questions:
Answers:

You can also try this:

public class StringReverse {
    public static void main(String[] args) {
        String str = "Dogs hates cats";
        StringBuffer sb = new StringBuffer(str);
        System.out.println(sb.reverse());
    }
}

Questions:
Answers:
public static void main(String[] args) {
    String str = "Prashant";
    int len = str.length();
    char[] c = new char[len];
    for (int j = len - 1, i = 0; j >= 0; j--, i++) {
        c[i] = str.charAt(j);
    }
    str = String.copyValueOf(c);
    System.out.println(str);
}

Questions:
Answers:

1. Using Character Array:

public String reverseSting(String inputString) {
    char[] inputStringArray = inputString.toCharArray();
    String reverseString = "";
    for (int i = inputStringArray.length - 1; i >= 0; i--) {
        reverseString += inputStringArray[i];
    }
    return reverseString;
}

2. Using StringBuilder:

public String reverseSting(String inputString) {
    StringBuilder stringBuilder = new StringBuilder(inputString);
    stringBuilder = stringBuilder.reverse();
    return stringBuilder.toString();
}

OR

return new StringBuilder(inputString).reverse().toString();

Questions:
Answers:

Reversing a String by Character:

public class Main {

    public static void main(String[] args) {

        String str1 = "whatever string something";

        StringBuffer str1buff = new StringBuffer(str1);

        String str1rev = str1buff.reverse().toString();

        System.out.println(str1rev);


    }
}

Reversing a String by Word:

public class Main {

public static void main(String[] args) {

    String str1 = "reverse this string";

    Stack<Object> stack = new Stack<>();

    StringTokenizer strTok = new StringTokenizer(str1);

    while(strTok.hasMoreTokens()){

        stack.push(strTok.nextElement());
    }

    StringBuffer str1rev = new StringBuffer();

    while(!stack.empty()){

        str1rev.append(stack.pop());
        str1rev.append(" ");


    }

    System.out.println(str1rev);



}
}

Questions:
Answers:

Procedure :

We can use split() to split the string .Then use reverse loop and add the characters.


Code snippet:

class test
{
  public static void main(String args[]) 
  {
      String str = "world";
      String[] split= str.split("");

      String revers = "";
      for (int i = split.length-1; i>=0; i--)
      {
        revers += split[i];
      }
      System.out.printf("%s", revers);
   }  
}

 //output : dlrow