Thursday, 17 March 2016

Best way to reverse the string


1. Use StringBuilder.reverse() or StringBuffer.reverse()String string = "abcdefghijklmnopqrstuvwxyz";
String reverse = new StringBuilder(string).reverse().toString();
// OR
String reverse = new StringBuffer(string).reverse().toString();


2. Without using StringBuilder.reverse() or StringBuffer.reverse()
Approach - 1
StringBuilder strBuilder = new StringBuilder();
char[ ] strChars = string.toCharArray();
for (int i = strChars.length - 1; i >= 0; i--) {
  strBuilder.append(strChars[i]);
}
String reverse = strBuilder.toString();

Approach - 2
char[ ] strChars = string.toCharArray();
char[ ] reverseChar = new char[strChars.length];
int counter = 0;
for (int i = strChars.length - 1; i >= 0; i--) {
  reverseChar[counter] = strChars[i] ;
  counter ++;
}
String reverse = new String(reverseChar);


The Genius way to reverse a string !
int len = string.length();
int mid = len/2;
char[ ] strChars = string.toCharArray();
int reverseCounter = len-1;

// iterate the string half way only
for (int counter=0; counter<mid; counter++) {
   // swap the characters in the same string array
    char tmpChar = strChars[counter];
    strChars[counter] = strChars[reverseCounter];
    strChars[reverseCounter] = tmpChar;
    reverseCounter - -;
}
String reverse = new String(strChars);

No comments:

Post a Comment

Note: only a member of this blog may post a comment.