553

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

Massimiliano Kraus
  • 3,433
  • 5
  • 24
  • 45
Ron
  • 6,203
  • 4
  • 22
  • 29
  • 9
    @JRL should really be String ih = "dlroW olleH"; System.out.println(ih); – Matthew Farwell Sep 27 '11 at 12:49
  • 4
    I wish I could retract my close vote (as a duplicate). I re-read the other question and realized it's subtly different than this. However, this question is still duplicated many times over across the site. Probably ought to just find a different question to mark this a dupe of. – Rob Hruska Sep 27 '11 at 13:31
  • see https://interviewquizandanswers.blogspot.com/2020/04/reverse-string.html – dasunse Apr 04 '20 at 09:38

50 Answers50

1139

You can use this:

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

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

M. Justin
  • 9,474
  • 3
  • 68
  • 98
Daniel Brockman
  • 17,912
  • 3
  • 27
  • 40
  • 14
    "Thanks commentators for pointing out that StringBuilder is preferred nowadays"? There is a clear statement that StringBuffer if thread-safety is a concern. otherwise, StringBuilder can be used. StringBuilder is not a replacement for StringBuffer. – ha9u63ar Jan 08 '15 at 13:51
  • 16
    @ha9u63ar For this scenario with a local throwaway `StringBuilder` concurrency is not a concern (and I think that's what he meant). – xehpuk Jan 16 '15 at 01:54
  • 2
    Here's the link to know the exact difference between the two: http://www.javatpoint.com/difference-between-stringbuffer-and-stringbuilder in short: StringBuilder is **more efficient** than StringBuffer. It's not thread safe i.e. multiple threads can simultaneously call methods of StringBuilder. – Vishnu Narang Feb 14 '17 at 03:17
  • This won't work for Unicode characters outside of BMP, as long as for combining characters. – nau Aug 17 '18 at 11:36
  • 2
    @Daniel Brockman, Thank you for your nice and concise answer. Here OP said, _I have "Hello World" kept in a String variable named hi_ . That means `String hi = "Hello World";` . So I think in your answer there should **not** be any double quotes around `hi`. I mean it should be like this `new StringBuilder(hi).reverse().toString()` – Md. Abu Nafee Ibna Zahid Aug 30 '18 at 12:59
  • Take into account that if you pass parameter different from `String` it will not correctly, so convert to `String` initially. – Dmytro Chasovskyi May 29 '19 at 12:24
119

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);
}
Sami Eltamawy
  • 9,680
  • 8
  • 47
  • 66
  • Just a note though. This will fail horribly for "characters" that occupy two bytes. – Minas Mina Jul 09 '18 at 06:04
  • 1
    Actually, it typically works fine for most characters that occupy 2 bytes. What it actually fails for is Unicode codepoints that occupy 2 x 16 bit codeunits (in UTF-16). – Stephen C Oct 08 '18 at 05:33
  • This is good solution, but can we do for the same if we have 10k characters in string with minimum complexity. – Jatinder Kumar Mar 02 '19 at 10:48
71
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

Kevin Bowersox
  • 90,944
  • 18
  • 150
  • 184
  • 4
    Good solution (1+). One enhancement - StringBuilder (since java5) will be faster than StringBuffer. Regards. – Michał Šrajer Sep 27 '11 at 12:49
  • 34
    This won't work in the general case as it doesn't take into account that some "characters" in unicode are represented by a surrogate pair i.e. two Java chars, and this solution results in the pair being in the wrong order. The reverse method of StringBuilder should be fine according to the JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse() – Ian Fairman Sep 16 '14 at 14:26
  • Does it reverse unicode diacriticals in the right order? – rogerdpack May 26 '21 at 16:39
67
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
30

I am doing this by using the following two ways:

Reverse string by CHARACTERS:

public static void main(String[] args) {
    // Using traditional 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);
}
Community
  • 1
  • 1
Vikasdeep Singh
  • 19,490
  • 9
  • 75
  • 99
20

Take a look at the Java 6 API under StringBuffer

String s = "sample";
String result = new StringBuffer(s).reverse().toString();
aioobe
  • 399,198
  • 105
  • 792
  • 807
Andrew Briggs
  • 1,311
  • 11
  • 25
  • is this better than StringBuilder? – CamHart Apr 11 '17 at 01:01
  • @CamHart No, it's slower, but probably only a tiny little bit. – jcsahnwaldt Reinstate Monica Feb 08 '18 at 18:01
  • 1
    A little benchmark with almost 100 million method calls showed a significant difference between StringBuffer and StringBuilder: https://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer/2771852#2771852 But in this case, there are only two calls (`reverse()` and `toString()`), so the difference probably won't even be measurable. – jcsahnwaldt Reinstate Monica Feb 08 '18 at 23:53
17

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);
}
C0D3LIC1OU5
  • 8,402
  • 2
  • 36
  • 45
  • 2
    There are already far better answers, especially @DanielBrockman's. If an algorithm already exists in a standard library, there is no need to handcraft it and reinvent the wheel. – Willi Mentzel Nov 03 '14 at 15:44
  • 17
    A "far better answer" concept is subjective. This may be exactly what someone is looking for. – C0D3LIC1OU5 Nov 03 '14 at 20:09
  • 2
    The OP already stated that "there is some kind of a function already built-in into Java that does that" so his goal was to know exactly which "function" this is. Just posting an answer that has little to do with the actual question asked is non-sense. If someone was to ask for a custom implementation your answer would be justified, in this case it is not. – Willi Mentzel Nov 12 '14 at 11:52
  • Downvote. Most other solutions are O(n) and can handle strings of pretty much any length, this one is O(n^2) and tends to crash with a StackOverflowError for strings longer than about 5000 chars (on JDK 8 VM, default config). – jcsahnwaldt Reinstate Monica Feb 08 '18 at 02:35
  • 1. The other solutions don't use recursion and can handle long strings just fine. Why would you use recursion instead of iteration for a task like this? It makes no sense. (Unless you're coming from a functional programming background, which often leads to problems when you're writing code in a imperative/OO language.) 2. String concatenation (that innocent little '+') is O(n). You must be new to Java, otherwise you would know that. – jcsahnwaldt Reinstate Monica Feb 08 '18 at 17:51
  • Here's a good explanation by Jon Skeet of the problem with that little '+' and strings: http://jonskeet.uk/csharp/stringbuilder.html (He's writing about C#, but it's pretty much the same thing in Java.) – jcsahnwaldt Reinstate Monica Feb 08 '18 at 17:54
  • 1
    Well, maybe you didn't read http://jonskeet.uk/csharp/stringbuilder.html , or maybe you didn't understand it. Hint: String concatenation is fine if you create a string in one fell swoop, but not if you build a string in a loop (and in this case, recursion is a loop). Yeah, I do get a bit personal when people post bad code on SO and don't even understand what's bad about it. Good bye. – jcsahnwaldt Reinstate Monica Feb 08 '18 at 22:22
13

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));
    }
}
Artur Grigio
  • 4,639
  • 7
  • 40
  • 61
13

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

public String reverseString(String s) {
    Stack<Character> stack = new Stack<>();
    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();

}
Enrico Giurin
  • 1,875
  • 28
  • 25
12

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

Prateek Joshi
  • 3,743
  • 3
  • 38
  • 50
12

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

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

But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.

The reason is that String represents 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"));
}
Ardent Coder
  • 3,499
  • 9
  • 25
  • 46
idelvall
  • 1,448
  • 14
  • 25
8

Using charAt() method

    String name = "gaurav";
    String reversedString = "";
    
    for(int i = name.length()-1; i>=0; i--){
      reversedString = reversedString + name.charAt(i);
    }
    System.out.println(reversedString);

Using toCharArray() method

String name = "gaurav";
    char [] stringCharArray = name.toCharArray();
    String reversedString = "";
    
    for(int i = stringCharArray.length-1; i>=0; i--) {
      reversedString = reversedString + stringCharArray[i];
    }
    System.out.println(reversedString);

Using reverse() method of the Stringbuilder

    String name = "gaurav";
    
    String reversedString = new StringBuilder(name).reverse().toString();
    
    System.out.println(reversedString);

Check https://coderolls.com/reverse-a-string-in-java/

Gaurav Kukade
  • 135
  • 2
  • 9
6

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));
            }
    }
}
mkobit
  • 39,564
  • 9
  • 145
  • 144
Neelendra
  • 79
  • 1
  • 2
4

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));
    }
}
DarkMental
  • 354
  • 5
  • 25
4

1. Using Character Array:

public String reverseString(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 reverseString(String inputString) {
    StringBuilder stringBuilder = new StringBuilder(inputString);
    stringBuilder = stringBuilder.reverse();
    return stringBuilder.toString();
}

OR

return new StringBuilder(inputString).reverse().toString();
Björn Lindqvist
  • 17,917
  • 18
  • 78
  • 117
Avijit Karmakar
  • 7,928
  • 6
  • 38
  • 57
3
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.

Stormhawks
  • 39
  • 1
3

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('"');
Sufiyan Ghori
  • 17,317
  • 13
  • 76
  • 106
2
    public String reverse(String s) {

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

        return reversedString;
    }
Dom Shahbazi
  • 702
  • 2
  • 9
  • 25
2

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());
    }
}
Emil Sierżęga
  • 1,528
  • 2
  • 31
  • 36
Anurag Goel
  • 470
  • 10
  • 15
  • 1
    there are many method to reverse a string.this is one of them using stringbuffer class of java.accepted answer is using diff class to reverse which is not available in older version of JDK. – Anurag Goel Nov 14 '14 at 16:37
2
public class Test {

public static void main(String args[]) {
   StringBuffer buffer = new StringBuffer("Game Plan");
   buffer.reverse();
   System.out.println(buffer);
 }  
}
Joby Wilson Mathews
  • 9,520
  • 4
  • 50
  • 47
2

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);

}

}
Dhiral Pandya
  • 9,739
  • 4
  • 45
  • 47
2

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

rashedcs
  • 3,209
  • 2
  • 35
  • 39
1
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);
}
Emil Sierżęga
  • 1,528
  • 2
  • 31
  • 36
  • 6
    Any answer to this question that *doesn't* use a built-in `reverse()` method is basically a wrong answer. –  Jul 21 '14 at 14:23
  • 2
    Agreed, especially as these "simple" solutions don't take into account surrogate pairs and can actually corrupt the string - see my comment above. – Ian Fairman Sep 16 '14 at 14:29
1

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;

}

Kelk
  • 67
  • 1
  • 7
1

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);

}
rvd
  • 161
  • 1
  • 1
  • 9
1
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){
  }
Deepak Singh
  • 454
  • 2
  • 7
  • 19
1

recursion:

 public String stringReverse(String string) {
    if (string == null || string.length() == 0) {
        return string;
    }
    return stringReverse(string.substring(1)) + string.charAt(0);
 }
connect2krish
  • 163
  • 2
  • 9
1
public static String revString(String str){
    char[] revCharArr = str.toCharArray();
    for (int i=0; i< str.length()/2; i++){
        char f = revCharArr[i];
        char l = revCharArr[str.length()-i-1];
        revCharArr[i] = l;
        revCharArr[str.length()-i-1] = f;
    }
    String revStr = new String(revCharArr);
    return revStr;
}
0
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!

Luís Cruz
  • 14,264
  • 16
  • 68
  • 94
Apetrei Ionut
  • 199
  • 2
  • 12
0
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);

}

}
Luís Cruz
  • 14,264
  • 16
  • 68
  • 94
0

Just For Fun..:)

Algorithm (str,len):
  char reversedStr[] =new reversedStr[len]
  Traverse i from 0 to len/2 and then
    reversedStr[i]=str[len-1-i]  
    reversedStr[len-1=i]=str[i]
  return reversedStr;

Time Complexity:O(n) Space Complexity :O(n)

 public class Reverse {
    static char reversedStr[];    
    public static void main(String[] args) {
        System.out.println(reversestr("jatin"));
    }        
    private static String reversestr(String str) {
        int strlen = str.length();
        reversedStr = new char[strlen];
        
        for (int i = 0; i <= strlen / 2; i++) {
            reversedStr[i] = str.charAt(strlen - 1 - i);
            reversedStr[strlen - 1 - i] = str.charAt(i);

        }
        return new String(reversedStr);
    }

}
jatin Goyal
  • 117
  • 6
0
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());
camel-man
  • 319
  • 1
  • 2
  • 9
0

There are many ways to reverse a string.

1. Converting String into Bytes: getBytes() method is used to convert the input string into bytes[].

import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
    String input = "GeeksforGeeks";
    byte [] strAsByteArray = input.getBytes();
    byte [] result =  new byte [strAsByteArray.length];

    for (int i = 0; i<strAsByteArray.length; i++)
        result[i] = 
         strAsByteArray[strAsByteArray.length-i-1];

    System.out.println(new String(result));
}
}

2.Converting String to character array: The user input the string to be reversed. (Personally suggested)

import java.lang.*;
import java.io.*;
import java.util.*;


class ReverseString{
public static void main(String[] args)
{
    String input = "GeeksForGeeks";

    // convert String to character array
    // by using toCharArray
    char[] try1 = input.toCharArray();

    for (int i = try1.length-1; i>=0; i--)
        System.out.print(try1[i]);
}
}

3.Using 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 LinkedList object which is a type of list of characters.

import java.lang.*;
import java.io.*;
import java.util.*;

 class ReverseString{

public static void main(String[] args)
{
    String input = "Geeks For Geeks";
    char[] hello = input.toCharArray();
    List<Character> trial1 = new ArrayList<>();

    for (char c: hello)
        trial1.add(c);

    Collections.reverse(trial1);
    ListIterator li = trial1.listIterator();
    while (li.hasNext())
        System.out.print(li.next());
}
}
vegetarianCoder
  • 2,254
  • 2
  • 15
  • 24
0

Everybody proposes a way to reverse string here. If you, the reader of the answer, are interested in, my way using \u202E unicode is here.

public static String reverse(String s) {
        return "\u202E" + s;
}

It can be tested from here.

It is just to print. If your aim is to pass a string in a reversed manner, you need to do it using loop or recursion.

snr
  • 16,197
  • 2
  • 61
  • 88
  • 1
    Didn't work. Trying to reverse "hello world" gives "?hello world" – Ricardo A. Apr 24 '19 at 16:45
  • @RicardoA. Apparently the problem stems from you, yet from the code. You can glance at the [link](https://ideone.com/owZB97) added in the answer as well. En passant, it is kinda trick just to show the output as reversed. If you put the returned string in an array char-by-char, it is possible to see that the order of the string is preserved except only `\u202E` character leads to it. – snr Apr 24 '19 at 18:12
  • 1
    Seems to be something specific to some IDE or other environment stuff, I copied the exact same code from the link and run with the same java version (not subversion though) in eclipse. It still gives me "?hello world". – Ricardo A. Apr 24 '19 at 19:18
  • Looks okay, but when I compare the strings like this: `"abcde".equals(reverse("edcba"))`, it doesn't match – gaffcz Dec 17 '19 at 08:46
  • @gaffcz have you ever read the bold text at the end of the post? – snr Dec 17 '19 at 09:09
0

Sequence of characters (or) StringString's Family:

String testString = "Yashwanth@777"; // ~1 1⁄4→D800₁₆«2²⁰

Using Java 8 Stream API

First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.

public static String reverseString_Stream(String str) {
    IntStream cahrStream = str.chars();
    final int[] array = cahrStream.map( x -> x ).toArray();

    int from = 0, upTo = array.length;
    IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );

    String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
            .mapToObj( reverseMapper )                 // array[ lastElement ]
            .collect(Collectors.joining())             // Joining stream of elements together into a String.
            .toString();                               // This object (which is already a string!) is itself returned.

    System.out.println("Reverse Stream as String : "+ reverseString);
    return reverseString;
}

Using a Traditional for Loop

If you want to reverse the string then we need to follow these steps.

  • Convert String into an Array of Characters.
  • Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
    if( reverse != null && reverse != "" && reverse.length() > 0 ) {

        char[] arr = reverse.toCharArray();
        String temp = "";
        for( int i = arr.length-1; i >= 0; i-- ) {
            temp += arr[i];
        }
        System.out.println("Reverse String : "+ temp);
    }
    return null;
}

Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes

StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.

StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );

String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString  );

StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.

Yash
  • 8,518
  • 2
  • 64
  • 71
0
    public static void reverseString(String s){
        System.out.println("---------");
        for(int i=s.length()-1; i>=0;i--){
            System.out.print(s.charAt(i));    
        }
        System.out.println(); 

    }
ultum
  • 112
  • 1
  • 9
  • This just outputs char of the string one by one. And also it can't be used anywhere in the program. It's much better to create a String variable, insert the "char" one by one into the string, then return the string. – Zombie Chibi XD Oct 29 '19 at 17:58
0

Simple For loop in java

 public void reverseString(char[] s) {
    int length = s.length;
    for (int i = 0; i < s.length / 2; i++) {
        // swaping character
        char temp = s[length - i - 1];
        s[length - i - 1] = s[i];
        s[i] = temp;
    }
}
0
    //Solution #1 -- Using array and charAt()
    String name = "reverse"; //String to reverse
    Character[] nameChar =  new Character[name.length()]; // Declaring a character array with length as length of the String which you want to reverse.
    for(int i=0;i<name.length();i++)// this will loop you through the String
    nameChar[i]=name.charAt(name.length()-1-i);// Using built in charAt() we can fetch the character at a given index. 
    for(char nam:nameChar)// Just to print the above nameChar character Array using an enhanced for loop
    System.out.print(nam);


    //Solution #2 - Using StringBuffer and reverse ().
    StringBuffer reverseString = new StringBuffer("reverse");
    System.out.println(reverseString.reverse()); //reverse () Causes the character sequence to be replaced by the reverse of the sequence.
abhi
  • 49
  • 1
  • 6
0
package ThingsInArray;

public class MagicWithSelectionSort {

    public static void main(String[] arg) {
        isSort("uhsnamiH");
    }

    private static void isSort(String name) {
        String revName="";
        for (int i = name.toCharArray().length-1; i >0 ; i--) {
            revName=revName+name.charAt(i);
        }
        System.out.println(revName);
    }

}
TheWildHealer
  • 1,453
  • 1
  • 14
  • 25
sachit
  • 31
  • 1
0

Without Using Arrays, you can store the Characters and concatenate them in reverse order.

public static String reverseString(String inpt) {

    String sb = "";
    for(int i = inpt.length()-1; i>=0; i--) {

        sb = sb.concat(""+inpt.charAt(i));
    }

    return sb;
}
karto
  • 3,278
  • 8
  • 41
  • 66
0

Here is the code that can be used to reverse a String.

public static void main(String[] args) {

        String aString = "noun";

        int size = aString.length();
        String reversed = "";

        for (int i=size-1;i>=0;i--){
            reversed = reversed+ aString.charAt(i);
            if (i == 0)
                System.out.println(reversed);
        }
}

you can also watch the video to better understand the concepts that are needed https://www.youtube.com/watch?v=KaoA0o2Tfi4

ChrisMM
  • 7,552
  • 11
  • 27
  • 44
Hasan
  • 21
  • 4
0

Having surrogate pairs in input string, you have to leave them not reversed, so good and generic way of reversing the string is using StringBuilder.reverse as it handles extended character set correctly. So called supplementary characters consisting of surrogate pairs are unicode values up to U+10FFFF encoded as two consecutive chars.

Here is my solution:

String aString = "abcdef";
String reversedString = aString
       .codePoints()
       .boxed()
       .map(Character::toString)
       .collect(Collectors.collectingAndThen(Collectors.toList(), aList -> {
           Collections.reverse(aList);
           return String.join("", aList);
       }));
  • String.codepoints returns stream of integers surrogate pair (double chars) packed in one integer, this is different that String.chars for which one integer = one char
  • as of Java 11 Character.toString also accepts codepoint, and returns either String of length 1 or 2 if there is surrogate pair
Dominik G
  • 534
  • 6
  • 8
0

You can use a for statement too:

      for (int y = 0; y < phrase.length(); y--){
      char ch = phrase.charAt(y-1);
      System.out.print(ch);
      }
  • Hi! Please edit your answer; It can't compile in its current form (missing semicolon & missing closing brace). – chornge Apr 21 '20 at 23:32
0

Just another method

private void revByFor() {
            String str="google";
            StringBuilder revStr= new StringBuilder();
            char[] str1= str.toCharArray();
            for (char c : str1) {
                revStr.insert(0, c);    
            }
            System.out.println(revStr); 
        }
Shubham Khare
  • 83
  • 1
  • 11
0
public class StringReverse1 {

public static void main(String[] args) {
    String name = "Vaquar khan";

    char array[] = name.toCharArray();
    System.out.println(name);
    System.out.println(reverseString(array));
}

private static String reverseString(char[] array) {
    String reverse = "";
    ///
    for (int i = array.length - 1; i >= 0; i--) {
        //System.out.println(array[i]);
        //
        reverse += array[i];
    }
    return reverse;

}

}

Results :

      Vaquar khan

      nahk rauqaV
vaquar khan
  • 9,473
  • 4
  • 64
  • 86
0

Yet another way is to use org.apache.commons.lang3.StringUtils#reverse

0

you can write without StringBuilder or with StringBuilder as follows:

private static boolean isPalindrome(int number){
    boolean isPalindrome = false;
    String original="", reversed="";
    original = String.valueOf(number);
        for(int y=original.length() -1; y >= 0; y--){
            reversed += original.charAt(y);
        }
        if(original.equals(reversed)){
            isPalindrome=true;
        }
        return isPalindrome;
}

private static boolean isPalindrome(String original){
    boolean isPalindrome = false;
    StringBuilder reversed=new StringBuilder(original).reverse();
    if(original.equals(reversed.toString())){
        isPalindrome=true;
    }
    return isPalindrome;
}

first method checks for a palindrome for an int and the other for a String.

Nomesh DeSilva
  • 1,635
  • 4
  • 24
  • 43
0
fun reverse(original: String): String {
    val toReserve = String(original.toByteArray(Charset.forName("UTF-16")), Charset.forName("UTF-16"))
    return StringBuilder(toReserve).reverse().toString()
}

Should work in Java/Kotlin with surrogate pairs.

K2mil J33
  • 169
  • 2
  • 14
-1
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 */
Holloway
  • 5,123
  • 1
  • 28
  • 31
Sandeep16
  • 21
  • 5
-2

Maybe using new StringBuilder(str).reverse.toString() is convenient and efficient enough. But if you wanna do it yourself, try this one:

public static String reverse(String str) {
    StringBuilder sb = new StringBuilder(str.length());
    for (int i = str.length() - 1; i >= 0; i--) {
        sb.append(str.charAt(i));
    }
    return sb.toString();
}

Some answers use str.toCharArray() to get this string's char array, this will result to allocate new memory to store these chars, which is not efficient.

StringBuffer is thread safe, but StringBuilder is not. So StringBuffer is less efficient than StringBuilder. If not necessary, use StringBuilder is a better practice.

Sniper Law
  • 53
  • 2
  • This will fail horribly for "characters" that occupy two bytes. – Minas Mina Jul 09 '18 at 06:03
  • Actually, it typically works fine for most characters that occupy 2 bytes. What it actually fails for is Unicode codepoints that occupy 2 x 16 bit codeunits (in UTF-16). – Stephen C Oct 08 '18 at 05:35