Created
November 19, 2012 23:20
-
-
Save tjFogarty/4114749 to your computer and use it in GitHub Desktop.
Reverse a string in java
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
public class ReverseString { | |
public static void main(String[] args) { | |
String reversed = reverseString( "Reverse this string." ); | |
System.out.println( reversed ); | |
} | |
public static String reverseString( String newString ) { | |
// cleans up string if there are any extra spaces | |
String myStringAfter = newString.trim().replaceAll(" +", " "); | |
// breaks string into an array that we can iterate through | |
String[] myStringArray = myStringAfter.split(""); | |
String reversed = ""; | |
int i; | |
for( i = myStringArray.length -1; i >= 0; i-- ) { | |
reversed += myStringArray[i]; | |
} | |
return reversed; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment