Skip to content

Instantly share code, notes, and snippets.

@janoulle
Created December 18, 2011 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janoulle/1493754 to your computer and use it in GitHub Desktop.
Save janoulle/1493754 to your computer and use it in GitHub Desktop.
Reversing a String
/**
* 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