Tuesday 8 December 2015

Reverse a String in Java

I recently asked about how to reverse a String using java.
there are couple of ways for doing this.
  1. Using StringBuilder or StringBuffer. former one is the newer and it's common now. you can read more about both on StringBuilder and StringBuffer. they are almost doing same thing.
  2. not using option 1...:)by saying that i mean like traversing the given string, character by character and just save it in reverse order from end toward the beginning. 
 Here is the code for both:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package reverseString;

public class Reverse {

 public static String reverseV1 (String input) {
  StringBuilder reversed = new StringBuilder(input.length());
  for (int i=input.length()-1; i>=0 ;i--) {
   reversed.append(input.charAt(i));
  }
  return reversed.toString();
 }
 
 public static String reverseV2 (String input) {
  String reversed ="";
  for (int i=input.length()-1; i>=0;i--) {
   reversed = reversed + input.charAt(i);
  }
  return reversed;
 }
 
 public static void main(String[] args) {
  
  System.out.println ("\"super\" in reverse (using V1): " + reverseV1("super"));
  System.out.println ("\"super\" in reverse (using V2): " + reverseV2("super"));
 }
}

Hope this helps.