Skip to content

Instantly share code, notes, and snippets.

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.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
//Print the reversed String
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.