Created
December 18, 2011 15:51
-
-
Save janoulle/1493754 to your computer and use it in GitHub Desktop.
Reversing a String
This file contains 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
/** | |
* Author: Jane Ullah | |
* Purpose: Reversing a string provided by the user. | |
* Date: 12/18/2011 | |
*/ | |
import java.util.Scanner; | |
public class ReversingString { | |
public static void main(String[] args) { | |
//Accept user input | |
Scanner keyboard = new Scanner(System.in); | |
System.out.print("Please enter a string to be reversed: "); | |
String userString = keyboard.nextLine(); | |
//StringBuffer to hold the reversed String | |
StringBuffer newString = new StringBuffer(); | |
int placeholder = userString.length(); | |
for (int i = (userString.length() - 1); i >= 0; i--) { | |
//Assumes words are separated by spaces | |
if (userString.charAt(i) == ' ') { | |
newString.append(userString.substring(i,placeholder).trim() + " "); | |
placeholder = i; | |
} | |
} | |
//Hold the final word | |
newString.append(userString.substring(0,placeholder).trim()); | |
//Print the reversed String | |
System.out.print(newString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment