Created
October 14, 2017 05:01
-
-
Save jsbonso/c15e3ab33e946d0be6e5d9ae8fe762ac to your computer and use it in GitHub Desktop.
[Java] Reverse a String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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