Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Created October 14, 2017 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbonso/c15e3ab33e946d0be6e5d9ae8fe762ac to your computer and use it in GitHub Desktop.
Save jsbonso/c15e3ab33e946d0be6e5d9ae8fe762ac to your computer and use it in GitHub Desktop.
[Java] Reverse a String
/**
* Reverses a string using StringBuilder.
* You can replace it with a StringBuffer as well,
* but in this case, you don't need it to be thread-safe,
* hence, a StringBuilder will do.
* @param input
* @return
*/
static String reverseString(String input) {
return (new StringBuilder(input)).reverse().toString();
}
/**
* Reverses a given String by transforming the
* input to a character array and then comparing
* its indices to check if it is the same.
* @param input
* @return
*/
static String reverseStringV2(String input) {
char[] charArray = input.toCharArray();
int endIndex = charArray.length - 1;
// We only need to iterate upto the middle of
// the array, to check each end.
for (int i=0; i <= (endIndex / 2); i++) {
char temp = charArray[i];
charArray[i] = charArray[endIndex - i];
charArray[endIndex - i] = temp;
}
return new String(charArray);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment