Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.